Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(session): filter GET /api/sessions by exact name

Yudhi Armyndharisb12f78a68c5f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9678d1971..97cd8eb1c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+
+- `GET /api/sessions` accepts a `name` query parameter that returns only the session with that exact name, also on the MCP `SessionFindAll` tool and the JavaScript, Python, Go, Java and PHP SDKs ([#1594](https://github.com/rmyndharis/OpenWA/issues/1594)). Thanks @rivenash.
+
### Changed
- The Italian (`it`) dashboard translates the session proxy Save button, the webhook chat-kind filter label and the warning shown when a backup export leaves out media ([#1583](https://github.com/rmyndharis/OpenWA/pull/1583)). Thanks @albanobattistella.
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 2f3938d43..991f56076 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -201,10 +201,11 @@ List all sessions, scoped to the API key's `allowedSessions`, ordered `createdAt
**Query parameters**
-| Name | Type | Required | Default | Description |
-| -------- | ---------------- | -------- | ------- | ----------------------------------------------------------------------------------------------- |
-| `limit` | integer (1-1000) | No | `1000` | Max sessions to return; oversized/non-finite values are clamped/fallback to the default window. |
-| `offset` | integer | No | `0` | Sessions to skip for paging; negative/non-finite values resolve to `0`. |
+| Name | Type | Required | Default | Description |
+| -------- | ---------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `limit` | integer (1-1000) | No | `1000` | Max sessions to return; oversized/non-finite values are clamped/fallback to the default window. |
+| `offset` | integer | No | `0` | Sessions to skip for paging; negative/non-finite values resolve to `0`. |
+| `name` | string | No | | Return only the session with exactly this name (case-sensitive). No match, including a name outside a scoped key's `allowedSessions`, returns `200 []`. An empty value or a repeated key returns `400`. |
**Response** `200`
@@ -241,7 +242,7 @@ List all sessions, scoped to the API key's `allowedSessions`, ordered `createdAt
`engineLoaded` reports whether the gateway holds a live engine for the session at the moment of the response. It is the precondition the lifecycle routes enforce, and **`status` is not a substitute for it**: `disconnected` covers both a session whose engine is still registered while an automatic reconnect backs off — where `POST /start` answers `400` — and one stopped through `POST /stop`, which has no engine and does need a start. When `engineLoaded` is `true`, `stop`, `logout` and `force-kill` can act; when it is `false`, `start` is the applicable route. The field is derived per request from live process state, so it is never persisted and never appears in historical/exported data.
-**Errors:** `401` missing/invalid `X-API-Key`
+**Errors:** `400` empty or repeated `name` · `401` missing/invalid `X-API-Key`
#### GET /api/sessions/:sessionId
diff --git a/openapi.json b/openapi.json
index ad0def342..024abab55 100644
--- a/openapi.json
+++ b/openapi.json
@@ -394,6 +394,15 @@
"schema": {
"type": "string"
}
+ },
+ {
+ "name": "name",
+ "required": false,
+ "in": "query",
+ "description": "Return only the session with exactly this name (case-sensitive); no match returns an empty array. An empty value or a repeated key is rejected with 400.",
+ "schema": {
+ "type": "string"
+ }
}
],
"responses": {
diff --git a/sdk/go/client_test.go b/sdk/go/client_test.go
index 6001aeb2f..464904d61 100644
--- a/sdk/go/client_test.go
+++ b/sdk/go/client_test.go
@@ -111,6 +111,18 @@ func TestJIDPathIsReadable(t *testing.T) {
}
}
+func TestListSessionsQueryName(t *testing.T) {
+ rt := &recordTransport{status: 200, body: `[]`}
+ c := newTestClient(t, rt)
+
+ if _, err := c.Sessions.List(context.Background(), &ListSessionsQuery{Name: Ptr("my-bot")}); err != nil {
+ t.Fatalf("List: %v", err)
+ }
+ if got := rt.lastReq.URL.RawQuery; got != "name=my-bot" {
+ t.Fatalf("query = %q, want %q", got, "name=my-bot")
+ }
+}
+
func TestQueryEncoding(t *testing.T) {
rt := &recordTransport{status: 200, body: `{"messages":[],"total":0}`}
c := newTestClient(t, rt)
diff --git a/sdk/go/types_session.go b/sdk/go/types_session.go
index ceb8384b6..5dc777537 100644
--- a/sdk/go/types_session.go
+++ b/sdk/go/types_session.go
@@ -5,16 +5,19 @@ import (
"net/url"
)
-// ListSessionsQuery paginates GET /sessions. Both fields optional.
+// ListSessionsQuery paginates GET /sessions. All fields optional.
type ListSessionsQuery struct {
Limit *int
Offset *int
+ // Name returns only the session with exactly this name (case-sensitive).
+ Name *string
}
func (q *ListSessionsQuery) values() url.Values {
v := url.Values{}
setInt(v, "limit", q.Limit)
setInt(v, "offset", q.Offset)
+ setStr(v, "name", q.Name)
return v
}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ListSessionsQuery.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ListSessionsQuery.java
index 5119ad1a1..d5090d7d6 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ListSessionsQuery.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ListSessionsQuery.java
@@ -1,7 +1,12 @@
package com.rmyndharis.openwa.model;
/** Query parameters for listing sessions. Null fields are omitted from the query string. */
-public record ListSessionsQuery(Integer limit, Integer offset) {
+public record ListSessionsQuery(Integer limit, Integer offset, String name) {
+ /** Paging only, without a name filter. */
+ public ListSessionsQuery(Integer limit, Integer offset) {
+ this(limit, offset, null);
+ }
+
public static Builder builder() {
return new Builder();
}
@@ -9,6 +14,7 @@ public record ListSessionsQuery(Integer limit, Integer offset) {
public static final class Builder {
private Integer limit;
private Integer offset;
+ private String name;
/** Maximum number of sessions to return. */
public Builder limit(Integer v) {
@@ -22,8 +28,14 @@ public record ListSessionsQuery(Integer limit, Integer offset) {
return this;
}
+ /** Return only the session with exactly this name (case-sensitive). */
+ public Builder name(String v) {
+ this.name = v;
+ return this;
+ }
+
public ListSessionsQuery build() {
- return new ListSessionsQuery(limit, offset);
+ return new ListSessionsQuery(limit, offset, name);
}
}
}
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/SessionsResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/SessionsResourceTest.java
index 51488d5be..fb0d46b49 100644
--- a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/SessionsResourceTest.java
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/SessionsResourceTest.java
@@ -6,6 +6,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import com.rmyndharis.openwa.ClientConfig;
import com.rmyndharis.openwa.OpenWAClient;
import com.rmyndharis.openwa.http.HttpMethod;
+import com.rmyndharis.openwa.model.ListSessionsQuery;
import com.rmyndharis.openwa.model.RequestPairingCodeRequest;
import com.rmyndharis.openwa.model.SetOwnPresenceRequest;
import com.rmyndharis.openwa.support.MockTransport;
@@ -24,6 +25,17 @@ class SessionsResourceTest {
assertEquals(HttpMethod.GET, tx.lastRequest().method());
}
+ @Test
+ void listSerializesNameFilter() {
+ tx.respond(200, "[]");
+ client.sessions.list(ListSessionsQuery.builder().name("my-bot").build());
+ assertEquals("http://h/api/sessions?name=my-bot", tx.lastRequest().url());
+
+ tx.respond(200, "[]");
+ client.sessions.list(new ListSessionsQuery(5, 0));
+ assertEquals("http://h/api/sessions?limit=5&offset=0", tx.lastRequest().url());
+ }
+
@Test
void getEncodesId() {
tx.respond(200, "{\"id\":\"a/b\",\"name\":\"n\",\"status\":\"ready\"}");
diff --git a/sdk/javascript/src/resources/sessions.ts b/sdk/javascript/src/resources/sessions.ts
index 055c19c05..2e5a13bb5 100644
--- a/sdk/javascript/src/resources/sessions.ts
+++ b/sdk/javascript/src/resources/sessions.ts
@@ -26,6 +26,8 @@ import type {
export interface ListSessionsQuery {
limit?: number;
offset?: number;
+ /** Return only the session with exactly this name (case-sensitive). */
+ name?: string;
}
export class SessionsResource {
diff --git a/sdk/javascript/test/sessions.test.ts b/sdk/javascript/test/sessions.test.ts
index da3143004..e305f1773 100644
--- a/sdk/javascript/test/sessions.test.ts
+++ b/sdk/javascript/test/sessions.test.ts
@@ -35,6 +35,12 @@ describe('SessionsResource — exact paths', () => {
expect(t.lastCall!.method).toBe('DELETE');
});
+ it('list serialises the name filter into the query string', async () => {
+ const t = new MockTransport().on('GET', /\/sessions$/, { body: [] });
+ await client(t).sessions.list({ name: 'my-bot', limit: 5 });
+ expect(t.lastCall!.url).toBe('http://x/api/sessions?name=my-bot&limit=5');
+ });
+
it('getQrCode / requestPairingCode / stats', async () => {
const t = new MockTransport()
.on('GET', /\/qr$/, { body: { qrCode: 'data:image/png;base64,xxx', status: 'qr_ready' } })
diff --git a/sdk/php/src/Resources/SessionsResource.php b/sdk/php/src/Resources/SessionsResource.php
index 9a04f19b7..41ef26c9d 100644
--- a/sdk/php/src/Resources/SessionsResource.php
+++ b/sdk/php/src/Resources/SessionsResource.php
@@ -21,7 +21,7 @@ class SessionsResource
}
/**
- * @param array<string,mixed> $query Optional pagination: `limit`, `offset`.
+ * @param array<string,mixed> $query Optional pagination `limit`, `offset`, and `name` for an exact, case-sensitive session name.
*
* @return array<int,array<string,mixed>>
*/
diff --git a/sdk/php/tests/ResourcesTest.php b/sdk/php/tests/ResourcesTest.php
index 2afe5ea5d..761d5306e 100644
--- a/sdk/php/tests/ResourcesTest.php
+++ b/sdk/php/tests/ResourcesTest.php
@@ -40,6 +40,15 @@ class ResourcesTest extends TestCase
$this->assertSame('DELETE', $backend->lastCall()['method']);
}
+ public function testSessionListSendsName(): void
+ {
+ $backend = new MockBackend();
+ $backend->on(200, []);
+ $client = $backend->makeClient();
+ $client->sessions->list(['name' => 'my-bot']);
+ $this->assertStringContainsString('name=my-bot', $backend->lastCall()['url']);
+ }
+
public function testQrPairingStats(): void
{
$backend = new MockBackend();
diff --git a/sdk/python/openwa/resources/sessions.py b/sdk/python/openwa/resources/sessions.py
index c84a62f13..08e8985b7 100644
--- a/sdk/python/openwa/resources/sessions.py
+++ b/sdk/python/openwa/resources/sessions.py
@@ -28,10 +28,14 @@ if TYPE_CHECKING:
class ListSessionsQuery(TypedDict, total=False):
- """Pagination for :meth:`SessionsResource.list`. The server applies its own default when omitted."""
+ """Pagination for :meth:`SessionsResource.list`. The server applies its own default when omitted.
+
+ ``name`` returns only the session with exactly that name (case-sensitive).
+ """
limit: int
offset: int
+ name: str
class SessionsResource:
diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.py
index 425cb89f4..1bcc86293 100644
--- a/sdk/python/tests/test_sdk.py
+++ b/sdk/python/tests/test_sdk.py
@@ -94,6 +94,11 @@ class TestClientCore:
client.sessions.list()
assert backend.last_call.url == "http://localhost:2785/api/sessions"
+ def test_sessions_list_sends_name(self):
+ backend = MockBackend().on("GET", "/api/sessions", body=[])
+ make_client(backend).sessions.list({"name": "my-bot"})
+ assert "name=my-bot" in backend.last_call.url
+
def test_query_params_skip_none(self):
backend = MockBackend().on("GET", "/messages", body=[])
make_client(backend).messages.list("s1", {"chatId": "[email protected]", "limit": 10})
diff --git a/src/core/agent-tools/tools/session.tools.spec.ts b/src/core/agent-tools/tools/session.tools.spec.ts
index 076881410..3bf016e22 100644
--- a/src/core/agent-tools/tools/session.tools.spec.ts
+++ b/src/core/agent-tools/tools/session.tools.spec.ts
@@ -35,6 +35,23 @@ describe('sessionTools', () => {
expect(out).toEqual([expect.objectContaining({ id: 's1', engineLoaded: true })]);
});
+ it('SessionFindAll forwards the name filter together with a scoped key allowlist', async () => {
+ const findAll = jest.fn().mockResolvedValue([]);
+ const auth = { ...makeAuth(), validateApiKey: jest.fn().mockResolvedValue({ id: 'k1', allowedSessions: ['s1'] }) };
+ const tool = makeTools({ findAll, isActive: jest.fn() } as unknown as SessionService).get('SessionFindAll')!;
+
+ await expect(invokeTool(tool, { name: 'other-bot' }, 'key', auth as unknown as AuthService)).resolves.toEqual([]);
+ expect(findAll).toHaveBeenCalledWith(['s1'], { limit: undefined, offset: undefined, name: 'other-bot' });
+ });
+
+ it('SessionFindAll rejects an empty name before reaching the service', async () => {
+ const findAll = jest.fn();
+ const tool = makeTools({ findAll } as unknown as SessionService).get('SessionFindAll')!;
+
+ await expect(run(tool, { name: '' })).rejects.toThrow();
+ expect(findAll).not.toHaveBeenCalled();
+ });
+
it('SessionFindOne delegates to findOne and maps to the response DTO', async () => {
const findOne = jest.fn().mockResolvedValue({ id: 's1', name: 'main', status: 'ready' });
const isActive = jest.fn().mockReturnValue(false);
diff --git a/src/core/agent-tools/tools/session.tools.ts b/src/core/agent-tools/tools/session.tools.ts
index 0fb75dd3a..909203b19 100644
--- a/src/core/agent-tools/tools/session.tools.ts
+++ b/src/core/agent-tools/tools/session.tools.ts
@@ -16,15 +16,16 @@ export function sessionTools(session: SessionService): AnyToolDescriptor[] {
defineTool({
name: 'SessionFindAll',
description:
- 'List the WhatsApp sessions this API key may access (id, name, status). Use to discover available sessions before calling session-scoped tools. Supports limit/offset paging.',
+ 'List the WhatsApp sessions this API key may access (id, name, status). Use to discover available sessions before calling session-scoped tools. Supports limit/offset paging and an exact, case-sensitive name filter.',
tier: 'read',
inputSchema: z.object({
limit: z.number().int().min(1).max(1000).optional(),
offset: z.number().int().min(0).optional(),
+ name: z.string().min(1).describe('Exact session name (case-sensitive)').optional(),
}),
handler: (input, apiKey) =>
session
- .findAll(apiKey.allowedSessions, { limit: input.limit, offset: input.offset })
+ .findAll(apiKey.allowedSessions, { limit: input.limit, offset: input.offset, name: input.name })
.then(ss => ss.map(s => SessionResponseDto.fromEntity(s, session.isActive(s.id)))),
}),
defineTool({
diff --git a/src/modules/session/session.controller.spec.ts b/src/modules/session/session.controller.spec.ts
index 327153793..542be34fc 100644
--- a/src/modules/session/session.controller.spec.ts
+++ b/src/modules/session/session.controller.spec.ts
@@ -5,6 +5,7 @@ import type { Session } from './entities/session.entity';
import type { SessionService } from './session.service';
import type { AuditService } from '../audit/audit.service';
import { AuditAction } from '../audit/entities/audit-log.entity';
+import type { ApiKey } from '../auth/entities/api-key.entity';
import { BadGatewayException, BadRequestException, ConflictException } from '@nestjs/common';
// POST /sessions declared a SessionResponseDto in its Swagger metadata but returned the raw
@@ -303,6 +304,43 @@ describe('SessionController — muteChat', () => {
});
});
+describe('SessionController findAll name filter', () => {
+ const apiKey = { allowedSessions: ['sess-uuid-1'] } as unknown as ApiKey;
+ let sessionService: { findAll: jest.Mock; isActive: jest.Mock };
+ let controller: SessionController;
+
+ beforeEach(() => {
+ sessionService = { findAll: jest.fn().mockResolvedValue([]), isActive: jest.fn().mockReturnValue(false) };
+ controller = new SessionControllerClass(
+ sessionService as unknown as SessionService,
+ { logInfo: jest.fn() } as unknown as AuditService,
+ );
+ });
+
+ it('forwards the name alongside the key allowlist and the window', async () => {
+ await expect(controller.findAll(apiKey, '10', '5', 'my-bot')).resolves.toEqual([]);
+
+ expect(sessionService.findAll).toHaveBeenCalledWith(['sess-uuid-1'], { limit: 10, offset: 5, name: 'my-bot' });
+ });
+
+ it('leaves the query unfiltered when name is absent', async () => {
+ await controller.findAll(apiKey);
+
+ expect(sessionService.findAll).toHaveBeenCalledWith(['sess-uuid-1'], {
+ limit: undefined,
+ offset: undefined,
+ name: undefined,
+ });
+ });
+
+ // A repeated key arrives as an array and an empty value as ''. Dropping either would return every
+ // session to a caller that asked for one, so both are refused before the service is reached.
+ it.each([[['a', 'b']], ['']])('rejects name=%p with 400', async name => {
+ await expect(controller.findAll(apiKey, undefined, undefined, name)).rejects.toBeInstanceOf(BadRequestException);
+ expect(sessionService.findAll).not.toHaveBeenCalled();
+ });
+});
+
// The pin route forwards a boolean the engine can refuse. The value worth pinning is that the
// engine's `false` reaches the caller: WhatsApp caps pinned chats at three, and a controller that
// hard-coded `{ success: true }` would report a refused pin as done.
diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.ts
index 165dcc9cb..ed46534cc 100644
--- a/src/modules/session/session.controller.ts
+++ b/src/modules/session/session.controller.ts
@@ -11,6 +11,7 @@ import {
HttpCode,
HttpStatus,
ParseUUIDPipe,
+ BadRequestException,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiQuery } from '@nestjs/swagger';
import { SessionService } from './session.service';
@@ -95,16 +96,31 @@ export class SessionController {
})
@ApiQuery({ name: 'limit', required: false, description: 'Max sessions to return (1-1000, default 1000)' })
@ApiQuery({ name: 'offset', required: false, description: 'Number of sessions to skip (for paging)' })
+ @ApiQuery({
+ name: 'name',
+ required: false,
+ type: String,
+ description:
+ 'Return only the session with exactly this name (case-sensitive); no match returns an empty array. ' +
+ 'An empty value or a repeated key is rejected with 400.',
+ })
async findAll(
@CurrentApiKey() apiKey?: ApiKey,
@Query('limit') limit?: string,
@Query('offset') offset?: string,
+ @Query('name') name?: string | string[],
): Promise<SessionResponseDto[]> {
+ // ?name=a&name=b arrives as an array and ?name= as ''; neither names one session, and silently
+ // dropping the filter would hand back every session instead.
+ if (Array.isArray(name) || name === '') {
+ throw new BadRequestException('name must be a single non-empty value');
+ }
// Scope to the key's allowedSessions so a session-restricted key cannot enumerate every
// session. A null/empty allowlist (e.g. ADMIN) still lists all.
const sessions = await this.sessionService.findAll(apiKey?.allowedSessions, {
limit: limit ? parseInt(limit, 10) : undefined,
offset: offset ? parseInt(offset, 10) : undefined,
+ name,
});
return sessions.map(s => this.transformSession(s));
}
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 66c2a6000..9c252a40a 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -782,6 +782,51 @@ describe('SessionService', () => {
skip: 0,
});
});
+
+ it('filters by exact name for an unrestricted key', async () => {
+ (repository.find as jest.Mock).mockResolvedValue([]);
+
+ await service.findAll(null, { name: 'My-Bot' });
+
+ expect(repository.find).toHaveBeenCalledWith({
+ where: { name: 'My-Bot' },
+ order: { createdAt: 'DESC', id: 'DESC' },
+ take: 1000,
+ skip: 0,
+ });
+ });
+
+ it('ANDs the name filter with the key allowlist in one where clause', async () => {
+ (repository.find as jest.Mock).mockResolvedValue([]);
+
+ await service.findAll(['sess-1'], { name: 'other-bot', limit: 10, offset: 5 });
+
+ expect(repository.find).toHaveBeenCalledWith({
+ where: { id: In(['sess-1']), name: 'other-bot' },
+ order: { createdAt: 'DESC', id: 'DESC' },
+ take: 10,
+ skip: 5,
+ });
+ });
+
+ it('never passes an empty or non-string name to the query', async () => {
+ (repository.find as jest.Mock).mockResolvedValue([]);
+
+ await service.findAll(null, { name: '' });
+ await service.findAll(['sess-1'], { name: ['a', 'b'] as unknown as string });
+
+ expect(repository.find).toHaveBeenNthCalledWith(1, {
+ order: { createdAt: 'DESC', id: 'DESC' },
+ take: 1000,
+ skip: 0,
+ });
+ expect(repository.find).toHaveBeenNthCalledWith(2, {
+ where: { id: In(['sess-1']) },
+ order: { createdAt: 'DESC', id: 'DESC' },
+ take: 1000,
+ skip: 0,
+ });
+ });
});
describe('findOne', () => {
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index e4bdb420e..de24b924a 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -11,7 +11,7 @@ import {
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { InjectRepository, InjectDataSource } from '@nestjs/typeorm';
-import { Repository, In, Not, IsNull, LessThan, DataSource, FindManyOptions } from 'typeorm';
+import { Repository, In, Not, IsNull, LessThan, DataSource, FindManyOptions, FindOptionsWhere } from 'typeorm';
import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
import { setTimeout } from 'node:timers/promises';
import { EngineTransportError } from '../../common/errors/engine-transport.error';
@@ -79,6 +79,11 @@ function isTransientLaunchFailure(error: unknown): boolean {
/** Pause between sequential auto-start launches so a burst of Chromium boots does not spike the host. */
export const AUTOSTART_THROTTLE_MS = 2_000;
+/** List window for {@link SessionService.findAll}, plus an optional exact session-name filter. */
+export interface SessionListOptions extends ListOptions {
+ name?: string;
+}
+
/**
* Statuses that assert an engine is running somewhere. The boot reset clears them for every row this
* node may claim; markLapsedDisconnected clears them for a row whose holder never came back, a
@@ -317,7 +322,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
return saved;
}
- async findAll(allowedSessions?: string[] | null, opts: ListOptions = {}): Promise<Session[]> {
+ async findAll(allowedSessions?: string[] | null, opts: SessionListOptions = {}): Promise<Session[]> {
// A session-restricted key only lists its own sessions; an unrestricted key (null/empty
// allowlist) lists all — mirroring the ApiKeyGuard allowedSessions model so a scoped key
// cannot enumerate every session through this aggregate route.
@@ -328,8 +333,17 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
take: limit,
skip: offset,
};
+ const where: FindOptionsWhere<Session> = {};
if (allowedSessions && allowedSessions.length > 0) {
- options.where = { id: In(allowedSessions) };
+ where.id = In(allowedSessions);
+ }
+ // Exact, case-sensitive match. Only a non-empty string reaches TypeORM: anything else (an
+ // array from a repeated query key, an empty value) is not a name and must not become one.
+ if (typeof opts.name === 'string' && opts.name.length > 0) {
+ where.name = opts.name;
+ }
+ if (Object.keys(where).length > 0) {
+ options.where = where;
}
const sessions = await this.sessionRepository.find(options);
return sessions.map(session => this.attachRuntimeState(session));
diff --git a/test/session-scope.e2e-spec.ts b/test/session-scope.e2e-spec.ts
index d86ee6bed..693cedca7 100644
--- a/test/session-scope.e2e-spec.ts
+++ b/test/session-scope.e2e-spec.ts
@@ -25,6 +25,8 @@ describe('Session-scoped query endpoints (e2e)', () => {
let app: INestApplication<App>;
let sessA: string;
let sessB: string;
+ let nameA: string;
+ let nameB: string;
let scopedKey: string; // ADMIN, allowedSessions: [sessA]
let adminKey: string; // ADMIN, unrestricted
let throwawayId: string; // a VIEWER key used as the :id target for key-management routes
@@ -44,6 +46,8 @@ describe('Session-scoped query endpoints (e2e)', () => {
const b = await sessionRepo.save(sessionRepo.create({ name: `e2e-scope-b-${Date.now()}` }));
sessA = a.id;
sessB = b.id;
+ nameA = a.name;
+ nameB = b.name;
// One audit row and one delivery-failure row per session, so a cross-tenant read has something to leak.
for (const sessionId of [sessA, sessB]) {
@@ -107,6 +111,32 @@ describe('Session-scoped query endpoints (e2e)', () => {
});
});
+ describe('GET /api/sessions?name=', () => {
+ const list = (key: string, query: string) =>
+ request(app.getHttpServer()).get(`/api/sessions?${query}`).set('X-API-Key', key);
+
+ it('returns only the exactly named session', async () => {
+ const res = await list(adminKey, `name=${nameB}`).expect(200);
+ expect((res.body as Session[]).map(s => s.id)).toEqual([sessB]);
+ });
+
+ it('matches case-sensitively and returns [] for an unknown name', async () => {
+ await list(adminKey, `name=${nameB.toUpperCase()}`).expect(200, []);
+ await list(adminKey, 'name=no-such-session').expect(200, []);
+ });
+
+ it('a scoped key gets [] for a name outside its allowlist, and its own session by name', async () => {
+ await list(scopedKey, `name=${nameB}`).expect(200, []);
+ const res = await list(scopedKey, `name=${nameA}`).expect(200);
+ expect((res.body as Session[]).map(s => s.id)).toEqual([sessA]);
+ });
+
+ it('rejects a repeated or empty name with 400', async () => {
+ await list(adminKey, `name=${nameA}&name=${nameB}`).expect(400);
+ await list(adminKey, 'name=').expect(400);
+ });
+ });
+
describe('GET /api/webhooks/delivery-failures', () => {
it('a key scoped to sessA sees sessA failures but never sessB', async () => {
const res = await request(app.getHttpServer())