Skip to content

Commit 37ec450

Browse files
committed
fix(integrations): honor negative position filters, type the new tests, and prove STARTTLS against a real SMTP server
1 parent 884b0d5 commit 37ec450

8 files changed

Lines changed: 166 additions & 44 deletions

File tree

‎apps/docs/content/docs/integrations/polymarket.mdx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -492,8 +492,8 @@ Retrieve user positions from Polymarket
492492
| `market` | string | No | Condition IDs to filter positions \(e.g., "0x1234...abcd,0x5678...efgh"\). Mutually exclusive with eventId. |
493493
| `eventId` | string | No | Event ID to filter positions \(e.g., "12345"\). Mutually exclusive with market. |
494494
| `sizeThreshold` | string | No | Minimum current position size in shares \(default: 0.1\) |
495-
| `redeemable` | string | No | Filter for redeemable positions only \(true/false\) |
496-
| `mergeable` | string | No | Filter for mergeable positions only \(true/false\) |
495+
| `redeemable` | string | No | true: only redeemable positions. false: drops redeemable positions from the returned page. |
496+
| `mergeable` | string | No | true: only mergeable positions. false: drops mergeable positions from the returned page. |
497497
| `sortBy` | string | No | Sort field: CURRENT_VALUE \(default\), TOKENS, PRICE, UNREALIZED_PNL, REALIZED_PNL, TOTAL_PNL, or TIMESTAMP |
498498
| `sortDirection` | string | No | Sort direction \(ASC or DESC\) |
499499
| `title` | string | No | Search filter by title |

‎apps/sim/blocks/blocks/jupyter.test.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,14 @@ describe('Jupyter block Create Session', () => {
1212
path: 'analysis.ipynb',
1313
type: 'file',
1414
}
15-
expect({ ...stored, ...JupyterBlock.tools.config.params(stored) }.type).toBeUndefined()
15+
expect(
16+
{ ...stored, ...JupyterBlock.tools.config.params(stored, undefined) }.type
17+
).toBeUndefined()
1618
})
1719

1820
it('sends the Session Type field, or the model type on an agent tool call', () => {
1921
const stored = { ...SERVER, operation: 'jupyter_create_session', sessionType: 'console' }
20-
expect(JupyterBlock.tools.config.params(stored).type).toBe('console')
22+
expect(JupyterBlock.tools.config.params(stored, undefined).type).toBe('console')
2123
expect(
2224
JupyterBlock.tools.config.params(
2325
{ ...SERVER, path: 'a.ipynb', type: 'console' },

‎apps/sim/blocks/blocks/ssh.test.ts‎

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,11 @@ describe('SSH block agent tool calls', () => {
1515
})
1616
})
1717

18+
/** Runs the block mapper as the canvas does (no context) or as an agent tool call for `operation`. */
19+
function mapParams(params: Record<string, unknown>, operation?: string): Record<string, unknown> {
20+
return SSHBlock.tools.config.params(params, operation ? { operation } : undefined)
21+
}
22+
1823
/** The executor sends `{ ...storedInputs, ...mapped }`, so a value stored for another operation must not leak in. */
1924
describe('SSH block canvas runs', () => {
2025
it('does not apply the upload permissions to Create Directory', () => {
@@ -24,7 +29,7 @@ describe('SSH block canvas runs', () => {
2429
createPath: '/srv/app',
2530
permissions: '0644',
2631
}
27-
expect({ ...stored, ...SSHBlock.tools.config.params(stored) }.permissions).toBeUndefined()
32+
expect({ ...stored, ...mapParams(stored) }.permissions).toBeUndefined()
2833
})
2934

3035
it('does not apply the Move/Rename overwrite switch to Upload File', () => {
@@ -36,17 +41,13 @@ describe('SSH block canvas runs', () => {
3641
remotePath: '/srv/a.txt',
3742
overwrite: false,
3843
}
39-
expect({ ...stored, ...SSHBlock.tools.config.params(stored) }.overwrite).toBeUndefined()
44+
expect({ ...stored, ...mapParams(stored) }.overwrite).toBeUndefined()
4045
})
4146

4247
it('keeps the model permissions and overwrite on an agent tool call', () => {
4348
const args = { ...CONNECTION, path: '/srv/app', permissions: '0700', overwrite: false }
44-
expect(
45-
SSHBlock.tools.config.params(args, { operation: 'ssh_create_directory' }).permissions
46-
).toBe('0700')
47-
expect(SSHBlock.tools.config.params(args, { operation: 'ssh_upload_file' }).overwrite).toBe(
48-
false
49-
)
49+
expect(mapParams(args, 'ssh_create_directory').permissions).toBe('0700')
50+
expect(mapParams(args, 'ssh_upload_file').overwrite).toBe(false)
5051
})
5152

5253
it('does not send a stored private key once the block is switched to password auth', () => {
@@ -57,7 +58,7 @@ describe('SSH block canvas runs', () => {
5758
privateKey: 'stale key',
5859
passphrase: 'stale passphrase',
5960
}
60-
expect({ ...stored, ...SSHBlock.tools.config.params(stored) }).toMatchObject({
61+
expect({ ...stored, ...mapParams(stored) }).toMatchObject({
6162
password: 'pw',
6263
privateKey: undefined,
6364
passphrase: undefined,
@@ -71,7 +72,7 @@ describe('SSH block canvas runs', () => {
7172
authMethod: 'privateKey',
7273
privateKey: 'key',
7374
}
74-
expect({ ...stored, ...SSHBlock.tools.config.params(stored) }).toMatchObject({
75+
expect({ ...stored, ...mapParams(stored) }).toMatchObject({
7576
privateKey: 'key',
7677
password: undefined,
7778
})

‎apps/sim/lib/internal/smtp/operations.test.ts‎

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -65,15 +65,6 @@ describe('SMTP operation', () => {
6565
)
6666
})
6767

68-
it('requires STARTTLS in TLS mode so credentials never go out in plaintext', async () => {
69-
await executeSmtpSend({ ...base, smtpPort: 587, smtpSecure: 'TLS' }, context)
70-
expect(mocks.send).toHaveBeenCalledWith(
71-
expect.objectContaining({ secure: false, requireTLS: true }),
72-
expect.anything(),
73-
context.signal
74-
)
75-
})
76-
7768
it('rejects unsafe SMTP destinations before creating a transport', async () => {
7869
mockValidateDatabaseHost.mockResolvedValue({ isValid: false, error: 'Private address' })
7970
await expect(executeSmtpSend(base, context)).rejects.toMatchObject({
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
import { createServer, type Server } from 'node:net'
2+
import {
3+
inputValidationMock,
4+
inputValidationMockFns,
5+
} from '@sim/testing/mocks/input-validation.mock'
6+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
7+
8+
vi.mock('@/lib/core/security/input-validation.server', () => inputValidationMock)
9+
vi.mock('@/lib/messaging/email/ehlo', () => ({ getSmtpEhloName: () => 'sim.example.com' }))
10+
11+
import { executeSmtpSend } from '@/lib/internal/smtp/operations'
12+
13+
const { mockValidateDatabaseHost } = inputValidationMockFns
14+
15+
/** A plaintext SMTP server that never offers STARTTLS and records every command it receives. */
16+
function startPlaintextSmtpServer(commands: string[]): Promise<{ server: Server; port: number }> {
17+
const server = createServer((socket) => {
18+
socket.on('error', () => {})
19+
let buffered = ''
20+
let inData = false
21+
socket.write('220 test ESMTP\r\n')
22+
socket.on('data', (chunk) => {
23+
buffered += chunk.toString()
24+
let lineEnd = buffered.indexOf('\r\n')
25+
while (lineEnd !== -1) {
26+
const line = buffered.slice(0, lineEnd)
27+
buffered = buffered.slice(lineEnd + 2)
28+
lineEnd = buffered.indexOf('\r\n')
29+
if (inData) {
30+
if (line === '.') {
31+
inData = false
32+
socket.write('250 queued\r\n')
33+
}
34+
continue
35+
}
36+
const command = line.split(' ')[0].toUpperCase()
37+
commands.push(command)
38+
if (command === 'EHLO') socket.write('250-test\r\n250 AUTH PLAIN LOGIN\r\n')
39+
else if (command === 'STARTTLS') socket.write('502 command not implemented\r\n')
40+
else if (command === 'AUTH') socket.write('235 authenticated\r\n')
41+
else if (command === 'DATA') {
42+
inData = true
43+
socket.write('354 go ahead\r\n')
44+
} else if (command === 'QUIT') socket.end('221 bye\r\n')
45+
else socket.write('250 ok\r\n')
46+
}
47+
})
48+
})
49+
return new Promise((resolve) => {
50+
server.listen(0, '127.0.0.1', () => {
51+
const address = server.address()
52+
resolve({ server, port: typeof address === 'object' && address ? address.port : 0 })
53+
})
54+
})
55+
}
56+
57+
describe('SMTP security modes against a server without STARTTLS', () => {
58+
let server: Server | undefined
59+
const commands: string[] = []
60+
61+
beforeEach(() => {
62+
commands.length = 0
63+
mockValidateDatabaseHost.mockResolvedValue({ isValid: true, resolvedIP: '127.0.0.1' })
64+
})
65+
66+
afterEach(async () => {
67+
await new Promise((resolve) => server?.close(resolve) ?? resolve(undefined))
68+
})
69+
70+
const send = async (smtpSecure: 'TLS' | 'None') => {
71+
const started = await startPlaintextSmtpServer(commands)
72+
server = started.server
73+
return executeSmtpSend(
74+
{
75+
smtpHost: 'smtp.example.com',
76+
smtpPort: started.port,
77+
smtpUsername: 'user',
78+
smtpPassword: 'password',
79+
smtpSecure,
80+
from: 'from@example.com',
81+
to: 'to@example.com',
82+
subject: 'Hello',
83+
body: 'Hello',
84+
},
85+
{ requestId: 'request-1', userId: 'user-1' }
86+
)
87+
}
88+
89+
it('fails in TLS mode before sending credentials', async () => {
90+
await expect(send('TLS')).rejects.toMatchObject({ status: 500 })
91+
expect(commands).toContain('EHLO')
92+
expect(commands).not.toContain('AUTH')
93+
expect(commands).not.toContain('MAIL')
94+
})
95+
96+
it('still sends in None mode, which allows a plaintext session', async () => {
97+
await expect(send('None')).resolves.toMatchObject({ success: true })
98+
expect(commands).toContain('AUTH')
99+
})
100+
})

‎apps/sim/tools/generated/tool-metadata.ts‎

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

‎apps/sim/tools/polymarket/data_api.test.ts‎

Lines changed: 36 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,28 @@ import { polymarketGetLeaderboardTool } from '@/tools/polymarket/get_leaderboard
33
import { polymarketGetPositionsTool } from '@/tools/polymarket/get_positions'
44
import { polymarketGetTradesTool } from '@/tools/polymarket/get_trades'
55

6-
const parseUrl = (url: unknown) => new URL(String(url))
6+
/** Builds the request URL a tool would call for `params`. */
7+
function requestUrl<P>(
8+
tool: { request: { url: string | ((params: P) => string) } },
9+
params: P
10+
): URL {
11+
const { url } = tool.request
12+
return new URL(typeof url === 'function' ? url(params) : url)
13+
}
714

815
/** The unversioned Data API v1 routes answer `410 Gone`; every Data tool must call v2. */
916
describe('Polymarket Data API v2', () => {
1017
it('sends v1-style position filters under their v2 names', () => {
11-
const url = parseUrl(
12-
polymarketGetPositionsTool.request.url({
13-
user: '0xabc',
14-
market: '0xcond',
15-
eventId: '42',
16-
sizeThreshold: '5',
17-
redeemable: 'true',
18-
sortBy: 'CURRENT',
19-
limit: '10',
20-
cursor: 'next-page',
21-
})
22-
)
18+
const url = requestUrl(polymarketGetPositionsTool, {
19+
user: '0xabc',
20+
market: '0xcond',
21+
eventId: '42',
22+
sizeThreshold: '5',
23+
redeemable: 'true',
24+
sortBy: 'CURRENT',
25+
limit: '10',
26+
cursor: 'next-page',
27+
})
2328
expect(url.pathname).toBe('/v2/positions')
2429
expect(Object.fromEntries(url.searchParams)).toEqual({
2530
user: '0xabc',
@@ -74,9 +79,9 @@ describe('Polymarket Data API v2', () => {
7479

7580
it("returns one wallet's volume rank from the v2 standing object", async () => {
7681
const params = { user: '0xw', orderBy: 'VOL' }
77-
expect(
78-
parseUrl(polymarketGetLeaderboardTool.request.url(params)).searchParams.get('sort_by')
79-
).toBe('VOLUME')
82+
expect(requestUrl(polymarketGetLeaderboardTool, params).searchParams.get('sort_by')).toBe(
83+
'VOLUME'
84+
)
8085
const body = { data: { user_id: '0xw', rank_pnl: 9, rank_volume: 3, volume: 10, pnl: 1 } }
8186
const result = await polymarketGetLeaderboardTool.transformResponse?.(
8287
new Response(JSON.stringify(body), { status: 200 }),
@@ -86,4 +91,19 @@ describe('Polymarket Data API v2', () => {
8691
expect.objectContaining({ rank: '3', proxyWallet: '0xw', vol: 10 }),
8792
])
8893
})
94+
95+
it('drops redeemable positions when Non-Redeemable Only is selected', async () => {
96+
const body = {
97+
data: [
98+
{ token_id: 'open', redeemable: false, mergeable: false },
99+
{ token_id: 'settled', redeemable: true, mergeable: false },
100+
],
101+
pagination: { has_more: false, next_cursor: null },
102+
}
103+
const result = await polymarketGetPositionsTool.transformResponse?.(
104+
new Response(JSON.stringify(body), { status: 200 }),
105+
{ user: '0xabc', redeemable: 'false' }
106+
)
107+
expect(result?.output.positions.map((position) => position.asset)).toEqual(['open'])
108+
})
89109
})

‎apps/sim/tools/polymarket/get_positions.ts‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -88,13 +88,15 @@ export const polymarketGetPositionsTool: ToolConfig<
8888
redeemable: {
8989
type: 'string',
9090
required: false,
91-
description: 'Filter for redeemable positions only (true/false)',
91+
description:
92+
'true: only redeemable positions. false: drops redeemable positions from the returned page.',
9293
visibility: 'user-or-llm',
9394
},
9495
mergeable: {
9596
type: 'string',
9697
required: false,
97-
description: 'Filter for mergeable positions only (true/false)',
98+
description:
99+
'true: only mergeable positions. false: drops mergeable positions from the returned page.',
98100
visibility: 'user-or-llm',
99101
},
100102
sortBy: {
@@ -161,15 +163,15 @@ export const polymarketGetPositionsTool: ToolConfig<
161163
}),
162164
},
163165

164-
transformResponse: async (response: Response) => {
166+
transformResponse: async (response: Response, params?: PolymarketGetPositionsParams) => {
165167
const data = await response.json()
166168

167169
if (!response.ok) {
168170
handlePolymarketError(data, response.status, 'get_positions')
169171
}
170172

171173
const { rows, page } = readDataPage(data)
172-
const positions: PolymarketPosition[] = rows.map((p) => ({
174+
const allPositions: PolymarketPosition[] = rows.map((p) => ({
173175
proxyWallet: (p.proxy_wallet as string) ?? null,
174176
asset: (p.token_id as string) ?? '',
175177
conditionId: (p.condition_id as string) ?? '',
@@ -197,6 +199,12 @@ export const polymarketGetPositionsTool: ToolConfig<
197199
negativeRisk: (p.negative_risk as boolean) ?? false,
198200
status: (p.status as string) ?? null,
199201
}))
202+
// v2 has no "not redeemable" or "not mergeable" status, so those filters apply to this page.
203+
const positions = allPositions.filter(
204+
(position) =>
205+
!(params?.redeemable === 'false' && position.redeemable) &&
206+
!(params?.mergeable === 'false' && position.mergeable)
207+
)
200208

201209
return {
202210
success: true,

0 commit comments

Comments
 (0)