Skip to content
Merged
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
74 changes: 74 additions & 0 deletions packages/backend/src/license/license-unclaimed.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -341,4 +341,78 @@ describe('LicenseService — paid licences that never reached their workspace',
expect(post).not.toHaveBeenCalled();
expect(setKey).not.toHaveBeenCalled();
});
describe('claimPaidLicenceFor: the purchase a workspace just made', () => {
it("asks the licence site for that workspace only and binds its fresh licence", async () => {
const { svc, setKey } = make({ orgs: ['org-b'] });
// Sold 10 seconds ago: the sweep would leave it for two minutes.
const post = siteLists([
{ key: KEY_B, email: 'bob@example.org', plan: 'starter', organizationId: 'org-b', createdAt: new Date(NOW.getTime() - 10_000).toISOString() },
]);

await expect(svc.claimPaidLicenceFor('org-b', NOW)).resolves.toBe(true);

expect(post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/license\/unclaimed$/),
{ organizationId: 'org-b' },
expect.objectContaining({ headers: { 'x-amcp-service-token': 'svc-token-0123456789abcdef' } }),
);
expect(setKey).toHaveBeenCalledWith(KEY_B, 'org-b');
});

it('binds nothing from the general list of an older licence site', async () => {
const { svc, setKey } = make({
orgs: ['org-b', 'org-c'],
users: [{ email: 'ann@example.com', role: 'ADMIN', organizationId: 'org-b', emailVerified: true }],
});
siteLists([
{ key: KEY_A, email: 'ann@example.com', plan: 'starter' },
{ key: KEY_B, email: 'carl@example.org', plan: 'team', organizationId: 'org-c' },
]);

await expect(svc.claimPaidLicenceFor('org-b', NOW)).resolves.toBe(false);
expect(setKey).not.toHaveBeenCalled();
});

it('leaves a workspace that already pays alone', async () => {
const { svc, setKey } = make({
orgs: ['org-b'],
locals: [{ licenseKey: 'AMCP-0000-1111-2222-3333', organizationId: 'org-b', plan: 'starter', status: 'active', expiresAt: null }],
});
siteLists([{ key: KEY_B, email: 'bob@example.org', plan: 'starter', organizationId: 'org-b' }]);

await expect(svc.claimPaidLicenceFor('org-b', NOW)).resolves.toBe(false);
expect(setKey).not.toHaveBeenCalled();
});

it('asks the site once per workspace in five seconds, whatever the page does', async () => {
const { svc } = make({ orgs: ['org-b', 'org-c'] });
const post = siteLists([]);

await svc.claimPaidLicenceFor('org-b', NOW);
await svc.claimPaidLicenceFor('org-b', new Date(NOW.getTime() + 4_000));
expect(post).toHaveBeenCalledTimes(1);
await svc.claimPaidLicenceFor('org-c', new Date(NOW.getTime() + 4_000));
expect(post).toHaveBeenCalledTimes(2);
await svc.claimPaidLicenceFor('org-b', new Date(NOW.getTime() + 5_000));
expect(post).toHaveBeenCalledTimes(3);
});

it('does nothing off Cloud, without the service token, or when the site fails', async () => {
const selfHosted = make({ orgs: ['org-b'], isCloud: false });
const post = siteLists([{ key: KEY_B, email: 'bob@example.org', plan: 'starter', organizationId: 'org-b' }]);
await expect(selfHosted.svc.claimPaidLicenceFor('org-b', NOW)).resolves.toBe(false);
expect(post).not.toHaveBeenCalled();

delete process.env.LICENSE_SERVICE_TOKEN;
const noToken = make({ orgs: ['org-b'] });
await expect(noToken.svc.claimPaidLicenceFor('org-b', NOW)).resolves.toBe(false);
expect(post).not.toHaveBeenCalled();

process.env.LICENSE_SERVICE_TOKEN = 'svc-token-0123456789abcdef';
const down = make({ orgs: ['org-b'] });
jest.spyOn(axios, 'post').mockRejectedValue(new Error('timeout'));
await expect(down.svc.claimPaidLicenceFor('org-b', NOW)).resolves.toBe(false);
expect(down.setKey).not.toHaveBeenCalled();
});
});
});
8 changes: 8 additions & 0 deletions packages/backend/src/license/license-unclaimed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,14 @@ export const UNCLAIMED_SWEEP_MS = 60 * 1000;
*/
export const UNCLAIMED_SETTLE_MS = 2 * 60 * 1000;

/**
* The shortest time between two requests to the licence site for one
* workspace's own purchase (LicenseService.claimPaidLicenceFor). The
* reactivation page asks every few seconds after a payment; the site sees
* one request per workspace in this time.
*/
export const WORKSPACE_CLAIM_MIN_INTERVAL_MS = 5 * 1000;

/** One entry of the licence site's answer. */
export interface UnclaimedLicence {
key: string;
Expand Down
116 changes: 90 additions & 26 deletions packages/backend/src/license/license.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
isSettled,
parseUnclaimedLicences,
UNCLAIMED_SWEEP_MS,
WORKSPACE_CLAIM_MIN_INTERVAL_MS,
type UnclaimedLicence,
type UnclaimedSkipReason,
} from './license-unclaimed';
Expand Down Expand Up @@ -983,32 +984,12 @@ export class LicenseService implements OnModuleInit, OnModuleDestroy {
// Too fresh: the buyer's browser may still be on its way back.
if (!isSettled(licence, now)) continue;
out.listed++;
const tail = licence.key.slice(-4);
try {
const target = await this.unclaimedLicenceTarget(licence, now);
if ('skip' in target) {
out.skipped++;
skipReasons.set(target.skip, (skipReasons.get(target.skip) ?? 0) + 1);
const log = `Unclaimed licence …${tail} (${maskEmail(licence.email)}) left unbound: ${target.skip}.`;
if (target.skip === 'already_paid' || target.skip === 'bound_elsewhere') warn(log);
else this.logger.debug(log);
continue;
}
if (target.retryActivation) {
if (!(await this.activateLicense(licence.key, target.organizationId))) {
out.failed++;
continue;
}
} else {
await this.setLicenseKey(licence.key, target.organizationId);
}
out.bound++;
this.logger.log(
`Bound paid licence …${tail} (${licence.plan}, ${maskEmail(licence.email)}) to workspace ${target.organizationId}.`,
);
} catch (err: any) {
out.failed++;
this.logger.warn(`Could not bind unclaimed licence …${tail}: ${err?.message ?? err}`);
const result = await this.bindListedLicence(licence, now, warn);
if (result === 'bound') out.bound++;
else if (result === 'failed') out.failed++;
else {
out.skipped++;
skipReasons.set(result.skip, (skipReasons.get(result.skip) ?? 0) + 1);
}
await new Promise((resolve) => setTimeout(resolve, 250));
}
Expand All @@ -1023,6 +1004,89 @@ export class LicenseService implements OnModuleInit, OnModuleDestroy {
return out;
}

/** Binds one listed licence to its workspace; says why when it is left alone. */
private async bindListedLicence(
licence: UnclaimedLicence,
now: Date,
warn: (msg: string) => void,
): Promise<'bound' | 'failed' | { skip: UnclaimedSkipReason }> {
const tail = licence.key.slice(-4);
try {
const target = await this.unclaimedLicenceTarget(licence, now);
if ('skip' in target) {
const log = `Unclaimed licence …${tail} (${maskEmail(licence.email)}) left unbound: ${target.skip}.`;
if (target.skip === 'already_paid' || target.skip === 'bound_elsewhere') warn(log);
else this.logger.debug(log);
return { skip: target.skip };
}
if (target.retryActivation) {
if (!(await this.activateLicense(licence.key, target.organizationId))) return 'failed';
} else {
await this.setLicenseKey(licence.key, target.organizationId);
}
this.logger.log(
`Bound paid licence …${tail} (${licence.plan}, ${maskEmail(licence.email)}) to workspace ${target.organizationId}.`,
);
return 'bound';
} catch (err: any) {
this.logger.warn(`Could not bind unclaimed licence …${tail}: ${err?.message ?? err}`);
return 'failed';
}
}

/** When each workspace last asked the licence site for its own purchase. */
private readonly workspaceClaims = new Map<string, number>();

/**
* Binds the paid licence a workspace just bought, without the two-minute
* wait of the sweep (bindUnclaimedPaidLicences).
*
* That wait gives the buyer's browser time to come back signed in and bind
* the licence itself. A checkout opened from the no-login reactivation page
* never does: its buyer comes back to that page, which calls this. Until
* 17 Nov 2026 they waited for the sweep, a median of 145 seconds and never
* under two minutes, while a purchase from the app's wall was active in 6:
* a buyer who went straight back to the chat was refused again.
*
* The licence site is asked for this workspace's unactivated licences only,
* and only those that name it are bound: an older site, which ignores the
* workspace and answers with its settled list, changes nothing here. One
* request per workspace every WORKSPACE_CLAIM_MIN_INTERVAL_MS, whatever the
* page does.
*/
async claimPaidLicenceFor(organizationId: string, now: Date = new Date()): Promise<boolean> {
if (!this.deployment.isCloud()) return false;
const headers = this.serviceHeaders();
if (!headers['x-amcp-service-token']) return false;

const last = this.workspaceClaims.get(organizationId);
if (last !== undefined && now.getTime() - last < WORKSPACE_CLAIM_MIN_INTERVAL_MS) return false;
for (const [org, at] of this.workspaceClaims) {
if (now.getTime() - at >= WORKSPACE_CLAIM_MIN_INTERVAL_MS) this.workspaceClaims.delete(org);
}
this.workspaceClaims.set(organizationId, now.getTime());

let licences: UnclaimedLicence[] | null;
try {
const { data } = await axios.post(
`${this.apiBase}/api/license/unclaimed`,
{ organizationId },
{ timeout: 10000, headers },
);
licences = parseUnclaimedLicences(data);
} catch (err: any) {
this.logger.debug(`Licence claim for workspace ${organizationId} failed: ${err?.message ?? err}`);
return false;
}
let bound = false;
for (const licence of licences ?? []) {
if (licence.organizationId !== organizationId) continue;
const result = await this.bindListedLicence(licence, now, (msg) => this.logger.warn(msg));
if (result === 'bound') bound = true;
}
return bound;
}

/** Where an unclaimed licence goes, or why it stays where it is. */
private async unclaimedLicenceTarget(
licence: UnclaimedLicence,
Expand Down
48 changes: 48 additions & 0 deletions packages/backend/src/license/reactivation.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ interface MakeOpts {
tokenMember?: any;
firstAdmin?: any;
checkout?: () => Promise<any>;
/** What LicenseService.claimPaidLicenceFor does for the workspace. */
claim?: (organizationId: string) => Promise<boolean>;
/** Adapter slugs of the workspace's connectors (null: a hand-made one). */
connectors?: Array<string | null>;
/** What the licence site answers for a win-back code. */
Expand Down Expand Up @@ -72,6 +74,7 @@ function make(opts: MakeOpts = {}) {
createCheckoutIntent: jest.fn<Promise<any>, [any]>(
opts.checkout ?? (async () => ({ url: 'https://checkout.stripe.test/s1', trial: false })),
),
claimPaidLicenceFor: jest.fn<Promise<boolean>, [string]>(opts.claim ?? (async () => false)),
};
const licenseGuard = {
getUsage: jest.fn().mockResolvedValue({
Expand Down Expand Up @@ -419,6 +422,51 @@ describe('ReactivationController', () => {
});
});

describe('POST /api/license/reactivate/:token/claim', () => {
it('binds the licence the workspace just bought and answers active', async () => {
const t = make({ lastInactive: license('trial', { status: 'expired', expiresAt: ended }) });
t.licenseService.claimPaidLicenceFor.mockImplementation(async () => {
// The binding makes the paid licence the workspace's current one.
t.licenseService.getCurrentLicense.mockResolvedValue(license('starter'));
return true;
});
await expect(t.controller.claim(token())).resolves.toEqual({ state: 'active' });
expect(t.licenseService.claimPaidLicenceFor).toHaveBeenCalledWith('org-1');
});

it('answers the unchanged state while the payment has not reached the licence site', async () => {
const t = make({ lastInactive: license('trial', { status: 'expired', expiresAt: ended }) });
await expect(t.controller.claim(token())).resolves.toEqual({ state: 'trial-ended' });
expect(t.licenseService.claimPaidLicenceFor).toHaveBeenCalledTimes(1);
});

it('asks nothing for a workspace that is already active', async () => {
const t = make({ current: license('starter') });
await expect(t.controller.claim(token())).resolves.toEqual({ state: 'active' });
expect(t.licenseService.claimPaidLicenceFor).not.toHaveBeenCalled();
});

it('keeps answering when the claim itself fails', async () => {
const t = make({
lastInactive: license('trial', { status: 'expired', expiresAt: ended }),
claim: async () => {
throw new Error('site down');
},
});
await expect(t.controller.claim(token())).resolves.toEqual({ state: 'trial-ended' });
});

it('answers 404 for an invalid token, a deleted workspace and on self-hosted', async () => {
const bad = make();
await expect(bad.controller.claim('x'.repeat(40))).rejects.toThrow(NotFoundException);
const gone = make({ org: null });
await expect(gone.controller.claim(token())).rejects.toThrow(NotFoundException);
const selfHosted = make({ cloud: false });
await expect(selfHosted.controller.claim(token())).rejects.toThrow(NotFoundException);
for (const t of [bad, gone, selfHosted]) expect(t.licenseService.claimPaidLicenceFor).not.toHaveBeenCalled();
});
});

describe('POST /api/license/reactivate/:token/event', () => {
it("records a click as the page's paywall_action, for the token's workspace and user", async () => {
const { controller, productEvents } = make();
Expand Down
32 changes: 29 additions & 3 deletions packages/backend/src/license/reactivation.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,11 @@ const INVALID_LINK = 'This link is invalid or has expired.';
* Never an address, a user or workspace id, or a licence key.
* - POST opens a pay-now Stripe Checkout for the workspace's administrator,
* with the same refusals as POST /api/license/checkout-link. The paid
* licence names the workspace, so the unclaimed-licence sweep
* (license-unclaimed.ts) binds it within a few minutes even when nobody
* signs in afterwards.
* licence names the workspace.
* - POST claim is what the page calls when the buyer is back from Stripe: it
* binds that licence at once (LicenseService.claimPaidLicenceFor). When
* the buyer never comes back, the unclaimed-licence sweep
* (license-unclaimed.ts) binds it within a few minutes.
*
* No session: the token (reactivation-token.ts) names the workspace and is
* the only credential, as with the trial extension link.
Expand Down Expand Up @@ -273,6 +275,30 @@ export class ReactivationController {
}
}

@Post(':token/claim')
@HttpCode(200)
// The page asks every few seconds after a payment, for a few minutes.
@Throttle({ default: { limit: 40, ttl: 60_000 } })
@ApiParam({ name: 'token', description: 'The reactivation link token' })
@ApiOperation({
summary:
'Cloud, no sign-in: back from Stripe, switch the workspace on with the licence it just bought (404 for an invalid or expired link)',
})
async claim(@Param('token') token: string): Promise<{ state: ReactivationState }> {
const { organizationId } = this.check(token);
const org = await this.prisma.organization.findUnique({ where: { id: organizationId }, select: { id: true } });
if (!org) throw new NotFoundException(INVALID_LINK);
// Only a licence the site sold for this very workspace is bound, so the
// link gives its holder nothing but what was paid for. A workspace that
// is already active has nothing to claim.
let { state } = await this.stateOf(organizationId);
if (state !== 'active') {
const bound = await this.licenseService.claimPaidLicenceFor(organizationId).catch(() => false);
if (bound) ({ state } = await this.stateOf(organizationId));
}
return { state };
}

@Post(':token/event')
@HttpCode(204)
// A page load reports 'shown', a few clicks and at most one leave.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,7 @@ export const MEMBER_VISIBILITY_ROUTES: Readonly<Record<string, RouteVisibility>>
'LicenseController.registerCommunity': admin(),
'ReactivationController.view': noSession('reactivation token'),
'ReactivationController.checkout': noSession('reactivation token'),
'ReactivationController.claim': noSession('reactivation token'),
'ReactivationController.event': noSession('reactivation token'),
'TrialExtensionController.confirm': noSession('signed e-mail link'),
'TrialExtensionController.extend': noSession('signed e-mail link'),
Expand Down
Loading
Loading