Skip to content

Commit 14d835f

Browse files
authored
v0.9.70: 1password patch path guard, trial reminder fix
2 parents f25f50f + e60f23d commit 14d835f

5 files changed

Lines changed: 129 additions & 11 deletions

File tree

‎apps/sim/lib/billing/free-plan.integration.ts‎

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,10 @@ import { executeSearchTool } from '@/lib/internal/search/execute-tool'
2121
import { applyScheduleRunFailureUpdate } from '@/background/schedule-execution'
2222

2323
const { stripeStub, mockSendEmail, mockNotifyScheduleAutoDisabled } = vi.hoisted(() => ({
24-
stripeStub: { subscriptions: { update: vi.fn() }, invoices: { createPreview: vi.fn() } },
24+
stripeStub: {
25+
subscriptions: { update: vi.fn(), retrieve: vi.fn() },
26+
invoices: { createPreview: vi.fn() },
27+
},
2528
mockSendEmail: vi.fn(),
2629
mockNotifyScheduleAutoDisabled: vi.fn(),
2730
}))
@@ -110,15 +113,21 @@ function search(userId: string, workspaceId: string) {
110113
})
111114
}
112115

116+
/** The subscriptions as Stripe holds them now, which the reminder reads back. */
117+
const liveSubscriptions = new Map<string, TrialEndingSubscription>()
118+
119+
/** A `trial_will_end` payload, which Stripe also holds as the live subscription. */
113120
function trialWillEnd(stripeSubscriptionId: string, status = 'trialing'): TrialEndingSubscription {
114-
return {
121+
const subscription = {
115122
id: stripeSubscriptionId,
116123
status,
117124
trial_end: Math.floor((Date.now() + 3 * DAY_MS) / 1000),
118125
items: {
119126
data: [{ quantity: 1, price: { unit_amount: 2500, recurring: { interval: 'month' } } }],
120127
},
121128
}
129+
liveSubscriptions.set(stripeSubscriptionId, subscription)
130+
return subscription
122131
}
123132

124133
async function addClaimedSchedule() {
@@ -152,6 +161,10 @@ beforeEach(() => {
152161
mockSendEmail.mockResolvedValue({ success: true })
153162
stripeStub.invoices.createPreview.mockReset()
154163
stripeStub.invoices.createPreview.mockResolvedValue({ amount_due: 2500 })
164+
stripeStub.subscriptions.retrieve.mockReset()
165+
stripeStub.subscriptions.retrieve.mockImplementation(async (id: string) =>
166+
liveSubscriptions.get(id)
167+
)
155168
mockNotifyScheduleAutoDisabled.mockReset()
156169
})
157170

@@ -280,6 +293,32 @@ describe('handleTrialWillEnd', () => {
280293

281294
expect(mockSendEmail).not.toHaveBeenCalled()
282295
})
296+
297+
it('sends nothing when the trial ended before the reminder arrived', async () => {
298+
const userId = await createUser()
299+
const stripeSubscriptionId = await addSubscription(userId, 'trialing')
300+
const event = trialWillEnd(stripeSubscriptionId)
301+
// A card that already had a trial ends the new one at once; the event still says trialing.
302+
liveSubscriptions.set(stripeSubscriptionId, { ...event, status: 'past_due', trial_end: null })
303+
304+
await handleTrialWillEnd(event)
305+
306+
expect(mockSendEmail).not.toHaveBeenCalled()
307+
})
308+
it('sends nothing for a reminder about an end date the trial no longer has', async () => {
309+
const userId = await createUser()
310+
const stripeSubscriptionId = await addSubscription(userId, 'trialing')
311+
const event = trialWillEnd(stripeSubscriptionId)
312+
// Still trialing, but its end moved after this event was sent.
313+
liveSubscriptions.set(stripeSubscriptionId, {
314+
...event,
315+
trial_end: (event.trial_end ?? 0) + 7 * 86_400,
316+
})
317+
318+
await handleTrialWillEnd(event)
319+
320+
expect(mockSendEmail).not.toHaveBeenCalled()
321+
})
283322
})
284323

285324
describe('endProTrial', () => {

‎apps/sim/lib/billing/webhooks/plan-notices.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,12 +68,15 @@ async function readRenewalCharge(
6868
* Handles Stripe's `customer.subscription.trial_will_end`, which arrives three days before a trial
6969
* converts: emails the trialing account the date, the charge, and how to cancel. Sent once per
7070
* subscription and trial end, however often Stripe redelivers the event.
71+
*
72+
* Reads the subscription as Stripe holds it now: the event's copy can predate a trial ended early
73+
* (a card that already had a trial is charged at once), and Stripe does not order its webhooks.
7174
*/
72-
export async function handleTrialWillEnd(
73-
stripeSubscription: TrialEndingSubscription
74-
): Promise<void> {
75+
export async function handleTrialWillEnd(event: TrialEndingSubscription): Promise<void> {
76+
const stripeSubscription: TrialEndingSubscription =
77+
await requireStripeClient().subscriptions.retrieve(event.id)
7578
const trialEnd = stripeSubscription.trial_end
76-
if (stripeSubscription.status !== 'trialing' || !trialEnd) return
79+
if (stripeSubscription.status !== 'trialing' || !trialEnd || trialEnd !== event.trial_end) return
7780

7881
const [recorded] = await db
7982
.select({ plan: subscription.plan, referenceId: subscription.referenceId })

‎apps/sim/lib/internal/onepassword/json-patch.test.ts‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import { describe, expect, it } from 'vitest'
2-
import { applyOnePasswordPatch } from '@/lib/internal/onepassword/json-patch'
2+
import {
3+
applyOnePasswordPatch,
4+
isSafeOnePasswordPatch,
5+
} from '@/lib/internal/onepassword/json-patch'
36

47
describe('applyOnePasswordPatch', () => {
58
it('resolves array segments by 1Password ID before numeric index', () => {
@@ -31,3 +34,40 @@ describe('applyOnePasswordPatch', () => {
3134
expect(item.tags).toEqual(['two'])
3235
})
3336
})
37+
38+
describe('prototype paths', () => {
39+
it.each(['/__proto__/polluted', '/constructor/prototype/polluted', '/fields/__proto__/polluted'])(
40+
'never writes through %s onto shared prototypes',
41+
(path) => {
42+
const item: Record<string, unknown> = { fields: [] }
43+
44+
applyOnePasswordPatch(item, { op: 'add', path, value: 'yes' })
45+
46+
expect(({} as Record<string, unknown>).polluted).toBeUndefined()
47+
expect(Object.hasOwn(Object.prototype, 'polluted')).toBe(false)
48+
}
49+
)
50+
51+
it('never walks into a property the item only inherits', () => {
52+
const shared: Record<string, unknown> = {}
53+
const item = Object.create({ section: shared }) as Record<string, unknown>
54+
55+
applyOnePasswordPatch(item, { op: 'add', path: '/section/label', value: 'yes' })
56+
57+
expect(shared).toEqual({})
58+
})
59+
60+
it('refuses a patch whose path reaches a prototype', () => {
61+
expect(isSafeOnePasswordPatch([{ op: 'add', path: '/__proto__/polluted', value: 1 }])).toBe(
62+
false
63+
)
64+
expect(isSafeOnePasswordPatch([{ op: 'replace', path: '/title', value: 'ok' }])).toBe(true)
65+
})
66+
67+
it.each(['test', 'copy', 'move', undefined])(
68+
'refuses a %s operation, which would otherwise be applied as a removal',
69+
(op) => {
70+
expect(isSafeOnePasswordPatch([{ op, path: '/title', value: 'keep' }])).toBe(false)
71+
}
72+
)
73+
})

‎apps/sim/lib/internal/onepassword/json-patch.ts‎

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,37 @@ function recordValue(value: unknown): Record<string, unknown> | undefined {
1010
: undefined
1111
}
1212

13+
/** Path segments that reach an object's prototype instead of its own data. */
14+
const PROTOTYPE_SEGMENTS = new Set(['__proto__', 'prototype', 'constructor'])
15+
16+
/** The operations 1Password's item patch accepts; anything else would be applied as a removal. */
17+
const PATCH_OPS = new Set<unknown>(['add', 'remove', 'replace'])
18+
19+
/**
20+
* Whether every operation is one 1Password accepts and its path names only an item's own data.
21+
* Patches are applied to a plain object in this process, so a path through `__proto__` would
22+
* write onto every object here.
23+
*/
24+
export function isSafeOnePasswordPatch(operations: unknown): operations is JsonPatchOperation[] {
25+
return (
26+
Array.isArray(operations) &&
27+
operations.every((operation) => {
28+
const record = recordValue(operation)
29+
const path = record?.path
30+
return (
31+
PATCH_OPS.has(record?.op) &&
32+
typeof path === 'string' &&
33+
path.split('/').every((segment) => !PROTOTYPE_SEGMENTS.has(segment))
34+
)
35+
})
36+
)
37+
}
38+
39+
/** A record's own property, never one inherited from its prototype. */
40+
function ownValue(record: Record<string, unknown> | undefined, key: string): unknown {
41+
return record && Object.hasOwn(record, key) ? record[key] : undefined
42+
}
43+
1344
function arrayIndexForSegment(target: unknown[], segment: string): number {
1445
const byId = target.findIndex((element) => recordValue(element)?.id === segment)
1546
if (byId !== -1) return byId
@@ -29,7 +60,7 @@ export function applyOnePasswordPatch(
2960
): void {
3061
const segments = operation.path.split('/').filter(Boolean)
3162
const rootKey = segments[0]
32-
if (!rootKey) return
63+
if (!rootKey || segments.some((segment) => PROTOTYPE_SEGMENTS.has(segment))) return
3364

3465
if (segments.length === 1) {
3566
if (operation.op === 'replace' || operation.op === 'add') {
@@ -47,7 +78,7 @@ export function applyOnePasswordPatch(
4778
if (Array.isArray(target)) {
4879
target = arrayElementForSegment(target, segment)
4980
} else {
50-
target = recordValue(target)?.[segment]
81+
target = ownValue(recordValue(target), segment)
5182
}
5283
if (target === undefined || target === null) return
5384
}

‎apps/sim/lib/internal/onepassword/operations.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ import {
3232
import { OnePasswordOperationError } from '@/lib/internal/onepassword/errors'
3333
import {
3434
applyOnePasswordPatch,
35-
type JsonPatchOperation,
35+
isSafeOnePasswordPatch,
3636
} from '@/lib/internal/onepassword/json-patch'
3737
import {
3838
createInternalToolFileResult,
@@ -276,7 +276,12 @@ export async function executeOnePasswordUpdateItem(
276276
context: OnePasswordOperationContext
277277
): Promise<unknown> {
278278
const credentials = resolveCredentials(input)
279-
const operations = JSON.parse(input.operations) as JsonPatchOperation[]
279+
const operations: unknown = JSON.parse(input.operations)
280+
if (!isSafeOnePasswordPatch(operations)) {
281+
throw new OnePasswordOperationError(400, {
282+
error: "Each patch operation needs a path to the item's own fields.",
283+
})
284+
}
280285
if (credentials.mode === 'service_account') {
281286
const client = await createOnePasswordClient(credentials.serviceAccountToken, context.signal)
282287
const existing = await runSdk(context.signal, () =>

0 commit comments

Comments
 (0)