Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(entitlement): add plan entitlements claiming (#1359)

Corentin Thomasset49761feccf3f
diff --git a/apps/papra-client/src/locales/en.dictionary.ts b/apps/papra-client/src/locales/en.dictionary.ts
index 10c2f8ed..35d5a8cf 100644
--- a/apps/papra-client/src/locales/en.dictionary.ts
+++ b/apps/papra-client/src/locales/en.dictionary.ts
@@ -1222,6 +1222,30 @@ export const translations = {
'You have used {{ percent }}% of your document storage. Consider upgrading your plan to get more space.',
'subscriptions.usage-warning.upgrade-button': 'Upgrade Plan',
+ // Plan entitlements
+
+ 'plan-entitlements.claim.selfhst.title': 'Claim your selfh.st perk',
+ 'plan-entitlements.claim.selfhst.description':
+ "As a selfh.st premium supporter, you're entitled to a bigger Papra free tier: twice the document storage, email intakes and members on all the free organizations you own.",
+ 'plan-entitlements.claim.selfhst.email-notice':
+ 'We will verify that your Papra account email {{ email }} has an active selfh.st premium subscription.',
+ 'plan-entitlements.claim.selfhst.claim-button': 'Claim perk',
+ 'plan-entitlements.claim.selfhst.success.title': 'Perk claimed!',
+ 'plan-entitlements.claim.selfhst.success.description':
+ 'Your extended free plan is now active on all the free organizations you own. Thank you for supporting the self-hosting ecosystem!',
+ 'plan-entitlements.claim.selfhst.already-claimed.title': 'Perk already claimed',
+ 'plan-entitlements.claim.selfhst.already-claimed.description':
+ 'Your selfh.st perk is already active on this account.',
+ 'plan-entitlements.claim.selfhst.errors.not-eligible':
+ 'We could not find an active selfh.st premium subscription for {{ email }}. Make sure your Papra account uses the same email as your selfh.st account.',
+ 'plan-entitlements.claim.selfhst.errors.claims-disabled':
+ 'Claiming this perk is currently disabled. Please try again later.',
+ 'plan-entitlements.claim.selfhst.errors.rate-limited':
+ 'Too many attempts. Please try again later.',
+ 'plan-entitlements.claim.selfhst.errors.generic':
+ 'Something went wrong while claiming your perk. Please try again later.',
+ 'plan-entitlements.claim.selfhst.go-to-app': 'Go to your documents',
+
// Admin
'admin.layout.header': 'Papra admin',
diff --git a/apps/papra-client/src/modules/plan-entitlements/pages/claim-selfhst.page.tsx b/apps/papra-client/src/modules/plan-entitlements/pages/claim-selfhst.page.tsx
new file mode 100644
index 00000000..7136c9e0
--- /dev/null
+++ b/apps/papra-client/src/modules/plan-entitlements/pages/claim-selfhst.page.tsx
@@ -0,0 +1,162 @@
+import type { Component } from 'solid-js';
+import { A, useNavigate } from '@solidjs/router';
+import { useMutation, useQuery, useQueryClient } from '@tanstack/solid-query';
+import { Match, onMount, Show, Switch } from 'solid-js';
+import { useI18n } from '@/modules/i18n/i18n.provider';
+import { isHttpErrorWithCode, isRateLimitError } from '@/modules/shared/http/http-errors';
+import { Button } from '@/modules/ui/components/button';
+import { useCurrentUser } from '@/modules/users/composables/useCurrentUser';
+import { claimPlanEntitlement, fetchUserPlanEntitlements } from '../plan-entitlements.services';
+import { UserSettingsDropdown } from '@/modules/users/components/user-settings.component';
+import { AppLogo } from '@/modules/ui/components/app-logo';
+import { useConfig } from '@/modules/config/config.provider';
+
+const SELFHST_ENTITLEMENT_TYPE = 'selfhst-premium';
+
+export const ClaimSelfhstPage: Component = () => {
+ const { t } = useI18n();
+ const { user } = useCurrentUser();
+ const queryClient = useQueryClient();
+ const { config } = useConfig();
+ const navigate = useNavigate();
+
+ onMount(() => {
+ if (!config.isSubscriptionsEnabled) {
+ navigate('/');
+ }
+ });
+
+ const entitlementsQuery = useQuery(() => ({
+ queryKey: ['plan-entitlements'],
+ queryFn: fetchUserPlanEntitlements,
+ }));
+
+ const claimMutation = useMutation(() => ({
+ mutationFn: async () => claimPlanEntitlement({ type: SELFHST_ENTITLEMENT_TYPE }),
+ onSettled: async () => queryClient.invalidateQueries({ queryKey: ['plan-entitlements'] }),
+ }));
+
+ const getIsAlreadyClaimed = () =>
+ entitlementsQuery.data?.planEntitlements.some(
+ (entitlement) =>
+ entitlement.type === SELFHST_ENTITLEMENT_TYPE &&
+ (entitlement.expiresAt === null || new Date(entitlement.expiresAt) > new Date()),
+ ) ?? false;
+
+ const getErrorMessage = () => {
+ const { error } = claimMutation;
+
+ if (!error) {
+ return undefined;
+ }
+
+ if (isHttpErrorWithCode({ error, code: 'plan_entitlements.already_exists' })) {
+ // The entitlements query is invalidated on settle, the refreshed data
+ // switches the page to the already-claimed state
+ return undefined;
+ }
+
+ if (isHttpErrorWithCode({ error, code: 'plan_entitlements.not_eligible' })) {
+ return t('plan-entitlements.claim.selfhst.errors.not-eligible', { email: user.email });
+ }
+
+ if (isHttpErrorWithCode({ error, code: 'plan_entitlements.claims_not_enabled' })) {
+ return t('plan-entitlements.claim.selfhst.errors.claims-disabled');
+ }
+
+ if (isRateLimitError({ error })) {
+ return t('plan-entitlements.claim.selfhst.errors.rate-limited');
+ }
+
+ return t('plan-entitlements.claim.selfhst.errors.generic');
+ };
+
+ return (
+ <div>
+ <div class="max-w-1000px mx-auto px-6 py-4 flex justify-between items-center">
+ <AppLogo as={A} href="/" />
+
+ <UserSettingsDropdown />
+ </div>
+
+ <div class="flex items-start justify-center min-h-screen p-6 bg-background sm:pt-24">
+ <div class="max-w-xl w-full text-center sm:border sm:p-12 sm:rounded-xl sm:bg-card">
+ <Switch>
+ <Match when={claimMutation.isSuccess || getIsAlreadyClaimed()}>
+ <div class="flex justify-center mb-6">
+ <div class="p-4 bg-primary/10 rounded-full">
+ <div class="i-tabler-check size-16 text-primary" />
+ </div>
+ </div>
+
+ <h1 class="text-3xl font-bold mb-3">
+ {t(
+ claimMutation.isSuccess
+ ? 'plan-entitlements.claim.selfhst.success.title'
+ : 'plan-entitlements.claim.selfhst.already-claimed.title',
+ )}
+ </h1>
+
+ <p class="text-muted-foreground mb-8">
+ {t(
+ claimMutation.isSuccess
+ ? 'plan-entitlements.claim.selfhst.success.description'
+ : 'plan-entitlements.claim.selfhst.already-claimed.description',
+ )}
+ </p>
+
+ <Button as={A} href="/" size="lg" class="w-full">
+ {t('plan-entitlements.claim.selfhst.go-to-app')}
+ <div class="i-tabler-arrow-right size-5 ml-2" />
+ </Button>
+ </Match>
+
+ <Match when={entitlementsQuery.isLoading}>
+ <div class="flex justify-center">
+ <div class="i-tabler-loader-2 size-10 animate-spin text-muted-foreground" />
+ </div>
+ </Match>
+
+ <Match when={true}>
+ <div class="flex justify-center mb-6">
+ <div class="p-4 bg-primary/10 rounded-full">
+ <div class="i-tabler-gift size-16 text-primary" />
+ </div>
+ </div>
+
+ <h1 class="text-3xl font-bold mb-3">{t('plan-entitlements.claim.selfhst.title')}</h1>
+
+ <p class="text-muted-foreground mb-4">
+ {t('plan-entitlements.claim.selfhst.description')}
+ </p>
+
+ <p class="text-muted-foreground mb-8 ">
+ {t('plan-entitlements.claim.selfhst.email-notice', { email: user.email })}
+ </p>
+
+ <Show when={getErrorMessage()}>
+ {(getMessage) => (
+ <p class="text-destructive text-sm mb-6" role="alert">
+ {getMessage()}
+ </p>
+ )}
+ </Show>
+
+ <Button
+ size="lg"
+ class="w-full"
+ onClick={() => claimMutation.mutate()}
+ disabled={claimMutation.isPending}
+ >
+ <Show when={claimMutation.isPending}>
+ <div class="i-tabler-loader-2 size-5 mr-2 animate-spin" />
+ </Show>
+ {t('plan-entitlements.claim.selfhst.claim-button')}
+ </Button>
+ </Match>
+ </Switch>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/apps/papra-client/src/modules/plan-entitlements/plan-entitlements.services.ts b/apps/papra-client/src/modules/plan-entitlements/plan-entitlements.services.ts
new file mode 100644
index 00000000..2360537b
--- /dev/null
+++ b/apps/papra-client/src/modules/plan-entitlements/plan-entitlements.services.ts
@@ -0,0 +1,29 @@
+import { apiClient } from '../shared/http/api-client';
+
+export type PlanEntitlement = {
+ id: string;
+ userId: string;
+ type: string;
+ source: string;
+ grantedAt: string;
+ expiresAt: string | null;
+ lastVerifiedAt: string | null;
+};
+
+export async function fetchUserPlanEntitlements() {
+ const { planEntitlements } = await apiClient<{ planEntitlements: PlanEntitlement[] }>({
+ method: 'GET',
+ path: '/api/plan-entitlements',
+ });
+
+ return { planEntitlements };
+}
+
+export async function claimPlanEntitlement({ type }: { type: string }) {
+ const { planEntitlement } = await apiClient<{ planEntitlement: PlanEntitlement }>({
+ method: 'POST',
+ path: `/api/plan-entitlements/${type}/claim`,
+ });
+
+ return { planEntitlement };
+}
diff --git a/apps/papra-client/src/routes.tsx b/apps/papra-client/src/routes.tsx
index a93fbf97..2cf988cb 100644
--- a/apps/papra-client/src/routes.tsx
+++ b/apps/papra-client/src/routes.tsx
@@ -1,7 +1,7 @@
import type { RouteDefinition } from '@solidjs/router';
import { Navigate, useParams } from '@solidjs/router';
import { useQuery } from '@tanstack/solid-query';
-import { Match, Show, Switch } from 'solid-js';
+import { Match, Show, Switch, lazy } from 'solid-js';
import { adminRoutes } from './modules/admin/admin.routes';
import { ApiKeysPage } from './modules/api-keys/pages/api-keys.page';
import { CreateApiKeyPage } from './modules/api-keys/pages/create-api-key.page';
@@ -246,6 +246,14 @@ export const routes: RouteDefinition[] = [
},
],
},
+ {
+ path: '/claim/selfhst',
+ component: lazy(async () =>
+ import('./modules/plan-entitlements/pages/claim-selfhst.page').then((module) => ({
+ default: module.ClaimSelfhstPage,
+ })),
+ ),
+ },
adminRoutes,
],
},
diff --git a/apps/papra-server/src/modules/admin/users/plan-entitlements/plan-entitlements.routes.ts b/apps/papra-server/src/modules/admin/users/plan-entitlements/plan-entitlements.routes.ts
index f26fc177..689d2baa 100644
--- a/apps/papra-server/src/modules/admin/users/plan-entitlements/plan-entitlements.routes.ts
+++ b/apps/papra-server/src/modules/admin/users/plan-entitlements/plan-entitlements.routes.ts
@@ -49,13 +49,12 @@ function registerGrantPlanEntitlementRoute({
const usersRepository = createUsersRepository({ db });
const planEntitlementsRepository = createPlanEntitlementsRepository({ db });
- await usersRepository.getUserByIdOrThrow({ userId });
-
const { planEntitlement } = await grantUserPlanEntitlement({
userId,
type,
expiresAt,
source: PLAN_ENTITLEMENT_SOURCES.ADMIN,
+ usersRepository,
planEntitlementsRepository,
planEntitlementDefinitionRegistry,
});
diff --git a/apps/papra-server/src/modules/app/server.routes.test.ts b/apps/papra-server/src/modules/app/server.routes.test.ts
index 19c83421..2f196bb7 100644
--- a/apps/papra-server/src/modules/app/server.routes.test.ts
+++ b/apps/papra-server/src/modules/app/server.routes.test.ts
@@ -23,7 +23,8 @@ function setValidParams(path: string) {
.replaceAll(':shareLinkId', 'dsl_333333333333333333333333')
.replaceAll(':shareLinkToken', 't'.repeat(SHARE_LINK_TOKEN_LENGTH))
.replaceAll(':documentViewId', 'dv_444444444444444444444444')
- .replaceAll(':planEntitlementId', 'pla_ent_555555555555555555555555');
+ .replaceAll(':planEntitlementId', 'pla_ent_555555555555555555555555')
+ .replaceAll(':type', 'selfhst-premium');
// throw if there are any remaining params
if (newPath.match(/:\w+/g)) {
diff --git a/apps/papra-server/src/modules/app/server.routes.ts b/apps/papra-server/src/modules/app/server.routes.ts
index 53d26c1b..585fb469 100644
--- a/apps/papra-server/src/modules/app/server.routes.ts
+++ b/apps/papra-server/src/modules/app/server.routes.ts
@@ -11,6 +11,7 @@ import { registerDocumentsRoutes } from '../documents/documents.routes';
import { registerIntakeEmailsRoutes } from '../intake-emails/intake-emails.routes';
import { registerInvitationsRoutes } from '../invitations/invitations.routes';
import { registerOrganizationsRoutes } from '../organizations/organizations.routes';
+import { registerPlanEntitlementsRoutes } from '../plan-entitlements/plan-entitlements.routes';
import { registerSubscriptionsRoutes } from '../subscriptions/subscriptions.routes';
import { registerTaggingRulesRoutes } from '../tagging-rules/tagging-rules.routes';
import { registerTagsRoutes } from '../tags/tags.routes';
@@ -40,5 +41,6 @@ export function registerRoutes(context: RouteDefinitionContext) {
registerDocumentActivityRoutes(context);
registerCustomPropertiesRoutes(context);
registerDocumentShareLinksRoutes(context);
+ registerPlanEntitlementsRoutes(context);
registerAdminRoutes(context);
}
diff --git a/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.config.ts b/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.config.ts
index 135e51d1..b7be2477 100644
--- a/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.config.ts
+++ b/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.config.ts
@@ -1,6 +1,14 @@
+import { rateLimitConfigSchema } from '../app/rate-limit/rate-limit.config.schemas';
import type { AppConfigDefinition } from '../config/config.types';
import { selfhstEntitlementsConfig } from './selfhst/selfhst.plan-entitlements.config';
export const planEntitlementsConfig = {
selfhst: selfhstEntitlementsConfig,
+ claimRateLimit: {
+ doc: 'The per-user rate limit for claiming plan entitlements',
+ schema: rateLimitConfigSchema,
+ default: '5/1h',
+ env: 'PLAN_ENTITLEMENTS_CLAIM_RATE_LIMIT',
+ showInDocumentation: false,
+ },
} as const satisfies AppConfigDefinition;
diff --git a/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.errors.ts b/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.errors.ts
index 652bf8d1..64b7ca75 100644
--- a/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.errors.ts
+++ b/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.errors.ts
@@ -23,3 +23,9 @@ export const createPlanEntitlementNotEligibleError = createErrorFactory({
code: 'plan_entitlements.not_eligible',
statusCode: 400,
});
+
+export const createPlanEntitlementClaimsNotEnabledError = createErrorFactory({
+ message: 'Claims for this entitlement are not enabled',
+ code: 'plan_entitlements.claims_not_enabled',
+ statusCode: 403,
+});
diff --git a/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.repository.ts b/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.repository.ts
index 733d9a3f..b9801c29 100644
--- a/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.repository.ts
+++ b/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.repository.ts
@@ -10,6 +10,7 @@ import type { Logger } from '@crowlog/logger';
import { createLogger } from '../shared/logger/logger';
import { isUniqueConstraintError } from '../shared/db/constraints.models';
import type { PlanEntitlementSource } from './plan-entitlements.constants';
+import { PLAN_ENTITLEMENT_SOURCES } from './plan-entitlements.constants';
import type { PlanEntitlementType } from './plan-entitlements.registry';
import {
createPlanEntitlementAlreadyExistsError,
@@ -30,8 +31,11 @@ export function createPlanEntitlementsRepository({
return injectArguments(
{
getActiveEntitlementForOrganization,
+ getActiveUserClaimedEntitlements,
getUserPlanEntitlements,
+ getUserPlanEntitlementByType,
createPlanEntitlement,
+ updatePlanEntitlement,
deleteUserPlanEntitlement,
},
{ db, clock, logger },
@@ -111,6 +115,78 @@ async function deleteUserPlanEntitlement({
}
}
+async function getActiveUserClaimedEntitlements({
+ db,
+ clock = systemClock,
+}: {
+ db: Database;
+ clock?: Clock;
+}) {
+ const now = new Date(clock.now().epochMilliseconds);
+
+ const planEntitlements = await db
+ .select()
+ .from(planEntitlementsTable)
+ .where(
+ and(
+ eq(planEntitlementsTable.source, PLAN_ENTITLEMENT_SOURCES.USER_CLAIM),
+ or(isNull(planEntitlementsTable.expiresAt), gt(planEntitlementsTable.expiresAt, now)),
+ ),
+ );
+
+ return { planEntitlements };
+}
+
+async function getUserPlanEntitlementByType({
+ db,
+ userId,
+ type,
+}: {
+ db: Database;
+ userId: string;
+ type: PlanEntitlementType;
+}) {
+ const [planEntitlement] = await db
+ .select()
+ .from(planEntitlementsTable)
+ .where(and(eq(planEntitlementsTable.userId, userId), eq(planEntitlementsTable.type, type)));
+
+ return { planEntitlement };
+}
+
+async function updatePlanEntitlement({
+ db,
+ planEntitlementId,
+ expiresAt,
+ lastVerifiedAt,
+ source,
+ grantedAt,
+}: {
+ db: Database;
+ planEntitlementId: string;
+ expiresAt: Date | null;
+ lastVerifiedAt: Date;
+ source?: PlanEntitlementSource;
+ grantedAt?: Date;
+}) {
+ const [planEntitlement] = await db
+ .update(planEntitlementsTable)
+ .set({
+ expiresAt,
+ lastVerifiedAt,
+ ...(source ? { source } : {}),
+ ...(grantedAt ? { grantedAt } : {}),
+ })
+ .where(eq(planEntitlementsTable.id, planEntitlementId))
+ .returning();
+
+ if (!planEntitlement) {
+ throw createPlanEntitlementNotFoundError();
+ }
+
+ return { planEntitlement };
+}
+
async function getActiveEntitlementForOrganization({
db,
organizationId,
diff --git a/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.routes.ts b/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.routes.ts
new file mode 100644
index 00000000..c8a016e3
--- /dev/null
+++ b/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.routes.ts
@@ -0,0 +1,72 @@
+import type { RouteDefinitionContext } from '../app/server.types';
+import * as v from 'valibot';
+import { requireAuthentication } from '../app/auth/auth.middleware';
+import { getUser } from '../app/auth/auth.models';
+import { scopeKvStoreForRateLimit } from '../app/rate-limit/rate-limit.kv-store';
+import { checkRateLimit } from '../app/rate-limit/rate-limit.usecases';
+import { joinKeyParts } from '../kv-store/kv-store.models';
+import { validateParams } from '../shared/validation/validation';
+import { createUsersRepository } from '../users/users.repository';
+import { createPlanEntitlementsRepository } from './plan-entitlements.repository';
+import { planEntitlementTypeSchema } from './plan-entitlements.schemas';
+import { claimUserPlanEntitlement } from './plan-entitlements.usecases';
+
+export function registerPlanEntitlementsRoutes(context: RouteDefinitionContext) {
+ setupGetUserPlanEntitlementsRoute(context);
+ setupClaimPlanEntitlementRoute(context);
+}
+
+function setupGetUserPlanEntitlementsRoute({ app, db }: RouteDefinitionContext) {
+ app.get('/api/plan-entitlements', requireAuthentication(), async (context) => {
+ const { userId } = getUser({ context });
+
+ const planEntitlementsRepository = createPlanEntitlementsRepository({ db });
+
+ const { planEntitlements } = await planEntitlementsRepository.getUserPlanEntitlements({
+ userId,
+ });
+
+ return context.json({ planEntitlements });
+ });
+}
+
+function setupClaimPlanEntitlementRoute({
+ app,
+ db,
+ config,
+ kvStore,
+ planEntitlementDefinitionRegistry,
+}: RouteDefinitionContext) {
+ app.post(
+ '/api/plan-entitlements/:type/claim',
+ requireAuthentication(),
+ validateParams(
+ v.strictObject({
+ type: planEntitlementTypeSchema,
+ }),
+ ),
+ async (context) => {
+ const { userId } = getUser({ context });
+ const { type } = context.req.valid('param');
+
+ await checkRateLimit({
+ ...config.planEntitlements.claimRateLimit,
+ key: joinKeyParts(['plan-entitlements-claim', userId]),
+ kvStore: scopeKvStoreForRateLimit({ kvStore }),
+ });
+
+ const usersRepository = createUsersRepository({ db });
+ const planEntitlementsRepository = createPlanEntitlementsRepository({ db });
+
+ const { planEntitlement } = await claimUserPlanEntitlement({
+ userId,
+ type,
+ usersRepository,
+ planEntitlementsRepository,
+ planEntitlementDefinitionRegistry,
+ });
+
+ return context.json({ planEntitlement });
+ },
+ );
+}
diff --git a/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.test-utils.ts b/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.test-utils.ts
index f7007843..3f3c3c60 100644
--- a/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.test-utils.ts
+++ b/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.test-utils.ts
@@ -9,6 +9,8 @@ export function createTestPlanEntitlementDriver(
planId: PLAN_IDS.FREE_EXTENDED,
verifyEligibility: async () => true,
getIsEnabledForNewClaims: async () => true,
+ claimValidityDuration: { hours: 45 * 24 },
+ ineligibilityGraceDuration: { hours: 7 * 24 },
...overrides,
};
}
diff --git a/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.types.ts b/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.types.ts
index 97c61c65..8d9d41cc 100644
--- a/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.types.ts
+++ b/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.types.ts
@@ -2,9 +2,11 @@ import type { Config } from '../config/config.types';
import type { PlanId } from '../plans/plans.constants';
export type PlanEntitlementDriver = {
- verifyEligibility: (params: { userId: string }) => Promise<boolean>;
+ verifyEligibility: (params: { user: { id: string; email: string } }) => Promise<boolean>;
getIsEnabledForNewClaims: () => Promise<boolean>;
planId: PlanId;
+ claimValidityDuration: Temporal.DurationLike;
+ ineligibilityGraceDuration: Temporal.DurationLike;
};
export type PlanEntitlementDriverFactoryParams = {
diff --git a/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.usecases.test.ts b/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.usecases.test.ts
index a27476db..fa8c00f6 100644
--- a/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.usecases.test.ts
+++ b/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.usecases.test.ts
@@ -1,13 +1,18 @@
import { describe, expect, test } from 'vitest';
import { createInMemoryDatabase } from '../app/database/database.test-utils';
import { createTestClock } from '../shared/clock/clock.test-utils';
+import { createUsersRepository } from '../users/users.repository';
import { createPlanEntitlementsRepository } from './plan-entitlements.repository';
import {
createEmptyTestPlanEntitlementRegistry,
createTestPlanEntitlementDriver,
createTestPlanEntitlementRegistry,
} from './plan-entitlements.test-utils';
-import { grantUserPlanEntitlement } from './plan-entitlements.usecases';
+import {
+ claimUserPlanEntitlement,
+ grantUserPlanEntitlement,
+ reverifyUserClaimedPlanEntitlements,
+} from './plan-entitlements.usecases';
describe('plan-entitlements usecases', () => {
describe('grantUserPlanEntitlement', () => {
@@ -17,6 +22,7 @@ describe('plan-entitlements usecases', () => {
});
const { clock } = createTestClock({ now: Temporal.Instant.from('2026-06-01T12:00:00Z') });
+ const usersRepository = createUsersRepository({ db });
const planEntitlementsRepository = createPlanEntitlementsRepository({ db, clock });
const planEntitlementDefinitionRegistry = createTestPlanEntitlementRegistry({
driver: createTestPlanEntitlementDriver({ verifyEligibility: async () => true }),
@@ -26,6 +32,7 @@ describe('plan-entitlements usecases', () => {
userId: 'usr_1',
type: 'selfhst-premium',
source: 'admin',
+ usersRepository,
planEntitlementsRepository,
planEntitlementDefinitionRegistry,
clock,
@@ -41,6 +48,7 @@ describe('plan-entitlements usecases', () => {
users: [{ id: 'usr_1', email: '[email protected]' }],
});
+ const usersRepository = createUsersRepository({ db });
const planEntitlementsRepository = createPlanEntitlementsRepository({ db });
const planEntitlementDefinitionRegistry = createTestPlanEntitlementRegistry({
driver: createTestPlanEntitlementDriver({ verifyEligibility: async () => false }),
@@ -51,6 +59,7 @@ describe('plan-entitlements usecases', () => {
userId: 'usr_1',
type: 'selfhst-premium',
source: 'admin',
+ usersRepository,
planEntitlementsRepository,
planEntitlementDefinitionRegistry,
}),
@@ -62,17 +71,18 @@ describe('plan-entitlements usecases', () => {
expect(planEntitlements).to.eql([]);
});
- test('the eligibility is verified for the target user', async () => {
+ test('the eligibility is verified with the target user id and email', async () => {
const { db } = await createInMemoryDatabase({
users: [{ id: 'usr_1', email: '[email protected]' }],
});
- const verifiedUserIds: string[] = [];
+ const verifiedUsers: { id: string; email: string }[] = [];
+ const usersRepository = createUsersRepository({ db });
const planEntitlementsRepository = createPlanEntitlementsRepository({ db });
const planEntitlementDefinitionRegistry = createTestPlanEntitlementRegistry({
driver: createTestPlanEntitlementDriver({
- verifyEligibility: async ({ userId }) => {
- verifiedUserIds.push(userId);
+ verifyEligibility: async ({ user }) => {
+ verifiedUsers.push({ id: user.id, email: user.email });
return true;
},
}),
@@ -82,11 +92,12 @@ describe('plan-entitlements usecases', () => {
userId: 'usr_1',
type: 'selfhst-premium',
source: 'admin',
+ usersRepository,
planEntitlementsRepository,
planEntitlementDefinitionRegistry,
});
- expect(verifiedUserIds).to.eql(['usr_1']);
+ expect(verifiedUsers).to.eql([{ id: 'usr_1', email: '[email protected]' }]);
});
test('when no driver exists for the entitlement type, an unknown-type error is raised', async () => {
@@ -94,6 +105,7 @@ describe('plan-entitlements usecases', () => {
users: [{ id: 'usr_1', email: '[email protected]' }],
});
+ const usersRepository = createUsersRepository({ db });
const planEntitlementsRepository = createPlanEntitlementsRepository({ db });
const planEntitlementDefinitionRegistry = createEmptyTestPlanEntitlementRegistry();
@@ -102,10 +114,454 @@ describe('plan-entitlements usecases', () => {
userId: 'usr_1',
type: 'selfhst-premium',
source: 'admin',
+ usersRepository,
planEntitlementsRepository,
planEntitlementDefinitionRegistry,
}),
).rejects.toThrowError('Unknown plan entitlement type');
});
});
+
+ describe('claimUserPlanEntitlement', () => {
+ test('when the user is eligible, the entitlement is created with the user-claim source and expires at the end of the driver validity window', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'usr_1', email: '[email protected]' }],
+ });
+ const { clock } = createTestClock({ now: Temporal.Instant.from('2026-06-01T12:00:00Z') });
+
+ const usersRepository = createUsersRepository({ db });
+ const planEntitlementsRepository = createPlanEntitlementsRepository({ db, clock });
+ const planEntitlementDefinitionRegistry = createTestPlanEntitlementRegistry({
+ driver: createTestPlanEntitlementDriver({
+ claimValidityDuration: { hours: 10 * 24 },
+ }),
+ });
+
+ const { planEntitlement } = await claimUserPlanEntitlement({
+ userId: 'usr_1',
+ type: 'selfhst-premium',
+ usersRepository,
+ planEntitlementsRepository,
+ planEntitlementDefinitionRegistry,
+ clock,
+ });
+
+ expect(planEntitlement?.source).to.eql('user-claim');
+ expect(planEntitlement?.expiresAt).to.eql(new Date('2026-06-11T12:00:00Z'));
+ expect(planEntitlement?.lastVerifiedAt).to.eql(new Date('2026-06-01T12:00:00Z'));
+ });
+
+ test('when new claims are disabled for the driver, a claims-not-enabled error is raised and no entitlement is created', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'usr_1', email: '[email protected]' }],
+ });
+
+ const usersRepository = createUsersRepository({ db });
+ const planEntitlementsRepository = createPlanEntitlementsRepository({ db });
+ const planEntitlementDefinitionRegistry = createTestPlanEntitlementRegistry({
+ driver: createTestPlanEntitlementDriver({
+ getIsEnabledForNewClaims: async () => false,
+ }),
+ });
+
+ await expect(
+ claimUserPlanEntitlement({
+ userId: 'usr_1',
+ type: 'selfhst-premium',
+ usersRepository,
+ planEntitlementsRepository,
+ planEntitlementDefinitionRegistry,
+ }),
+ ).rejects.toThrowError('Claims for this entitlement are not enabled');
+
+ const { planEntitlements } = await planEntitlementsRepository.getUserPlanEntitlements({
+ userId: 'usr_1',
+ });
+ expect(planEntitlements).to.eql([]);
+ });
+
+ test('when the user is not eligible, a not-eligible error is raised', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'usr_1', email: '[email protected]' }],
+ });
+
+ const usersRepository = createUsersRepository({ db });
+ const planEntitlementsRepository = createPlanEntitlementsRepository({ db });
+ const planEntitlementDefinitionRegistry = createTestPlanEntitlementRegistry({
+ driver: createTestPlanEntitlementDriver({ verifyEligibility: async () => false }),
+ });
+
+ await expect(
+ claimUserPlanEntitlement({
+ userId: 'usr_1',
+ type: 'selfhst-premium',
+ usersRepository,
+ planEntitlementsRepository,
+ planEntitlementDefinitionRegistry,
+ }),
+ ).rejects.toThrowError('User is not eligible for this entitlement');
+ });
+
+ test('when the user already has an active entitlement of the same type, an already-exists error is raised without verifying the eligibility', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'usr_1', email: '[email protected]' }],
+ planEntitlements: [
+ {
+ id: 'pla_ent_aaaaaaaaaaaaaaaaaaaaaaaa',
+ userId: 'usr_1',
+ type: 'selfhst-premium',
+ source: 'user-claim',
+ grantedAt: new Date('2026-01-01'),
+ },
+ ],
+ });
+
+ let verificationCount = 0;
+ const usersRepository = createUsersRepository({ db });
+ const planEntitlementsRepository = createPlanEntitlementsRepository({ db });
+ const planEntitlementDefinitionRegistry = createTestPlanEntitlementRegistry({
+ driver: createTestPlanEntitlementDriver({
+ verifyEligibility: async () => {
+ verificationCount += 1;
+ return true;
+ },
+ }),
+ });
+
+ await expect(
+ claimUserPlanEntitlement({
+ userId: 'usr_1',
+ type: 'selfhst-premium',
+ usersRepository,
+ planEntitlementsRepository,
+ planEntitlementDefinitionRegistry,
+ }),
+ ).rejects.toThrowError('User already has an entitlement of this type');
+
+ expect(verificationCount).to.eql(0);
+ });
+
+ test('when the user has an expired entitlement of the same type, it is re-activated in place instead of raising an already-exists error', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'usr_1', email: '[email protected]' }],
+ planEntitlements: [
+ {
+ id: 'pla_ent_aaaaaaaaaaaaaaaaaaaaaaaa',
+ userId: 'usr_1',
+ type: 'selfhst-premium',
+ source: 'admin',
+ grantedAt: new Date('2026-01-01T00:00:00Z'),
+ expiresAt: new Date('2026-02-01T00:00:00Z'),
+ lastVerifiedAt: new Date('2026-01-01T00:00:00Z'),
+ },
+ ],
+ });
+ const { clock } = createTestClock({ now: Temporal.Instant.from('2026-06-01T12:00:00Z') });
+
+ const usersRepository = createUsersRepository({ db });
+ const planEntitlementsRepository = createPlanEntitlementsRepository({ db, clock });
+ const planEntitlementDefinitionRegistry = createTestPlanEntitlementRegistry({
+ driver: createTestPlanEntitlementDriver({
+ claimValidityDuration: { hours: 10 * 24 },
+ }),
+ });
+
+ const { planEntitlement } = await claimUserPlanEntitlement({
+ userId: 'usr_1',
+ type: 'selfhst-premium',
+ usersRepository,
+ planEntitlementsRepository,
+ planEntitlementDefinitionRegistry,
+ clock,
+ });
+
+ expect(planEntitlement?.id).to.eql('pla_ent_aaaaaaaaaaaaaaaaaaaaaaaa');
+ expect(planEntitlement?.source).to.eql('user-claim');
+ expect(planEntitlement?.grantedAt).to.eql(new Date('2026-06-01T12:00:00Z'));
+ expect(planEntitlement?.expiresAt).to.eql(new Date('2026-06-11T12:00:00Z'));
+ expect(planEntitlement?.lastVerifiedAt).to.eql(new Date('2026-06-01T12:00:00Z'));
+
+ const { planEntitlements } = await planEntitlementsRepository.getUserPlanEntitlements({
+ userId: 'usr_1',
+ });
+ expect(planEntitlements).to.have.length(1);
+ });
+ });
+
+ describe('reverifyUserClaimedPlanEntitlements', () => {
+ test('active user-claimed entitlements of still-eligible users get their expiration rolled forward and verification date updated', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'usr_1', email: '[email protected]' }],
+ planEntitlements: [
+ {
+ id: 'pla_ent_aaaaaaaaaaaaaaaaaaaaaaaa',
+ userId: 'usr_1',
+ type: 'selfhst-premium',
+ source: 'user-claim',
+ grantedAt: new Date('2026-05-01T00:00:00Z'),
+ expiresAt: new Date('2026-06-10T00:00:00Z'),
+ lastVerifiedAt: new Date('2026-05-01T00:00:00Z'),
+ },
+ ],
+ });
+ const { clock } = createTestClock({ now: Temporal.Instant.from('2026-06-01T12:00:00Z') });
+
+ const usersRepository = createUsersRepository({ db });
+ const planEntitlementsRepository = createPlanEntitlementsRepository({ db, clock });
+ const planEntitlementDefinitionRegistry = createTestPlanEntitlementRegistry({
+ driver: createTestPlanEntitlementDriver({
+ verifyEligibility: async () => true,
+ claimValidityDuration: { hours: 10 * 24 },
+ }),
+ });
+
+ await reverifyUserClaimedPlanEntitlements({
+ usersRepository,
+ planEntitlementsRepository,
+ planEntitlementDefinitionRegistry,
+ clock,
+ });
+
+ const { planEntitlements } = await planEntitlementsRepository.getUserPlanEntitlements({
+ userId: 'usr_1',
+ });
+
+ expect(planEntitlements[0]?.expiresAt).to.eql(new Date('2026-06-11T12:00:00Z'));
+ expect(planEntitlements[0]?.lastVerifiedAt).to.eql(new Date('2026-06-01T12:00:00Z'));
+ });
+
+ test('entitlements of no-longer-eligible users get their expiration capped to the grace period', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'usr_1', email: '[email protected]' }],
+ planEntitlements: [
+ {
+ id: 'pla_ent_aaaaaaaaaaaaaaaaaaaaaaaa',
+ userId: 'usr_1',
+ type: 'selfhst-premium',
+ source: 'user-claim',
+ grantedAt: new Date('2026-05-01T00:00:00Z'),
+ expiresAt: new Date('2026-07-10T00:00:00Z'),
+ lastVerifiedAt: new Date('2026-05-01T00:00:00Z'),
+ },
+ ],
+ });
+ const { clock } = createTestClock({ now: Temporal.Instant.from('2026-06-01T12:00:00Z') });
+
+ const usersRepository = createUsersRepository({ db });
+ const planEntitlementsRepository = createPlanEntitlementsRepository({ db, clock });
+ const planEntitlementDefinitionRegistry = createTestPlanEntitlementRegistry({
+ driver: createTestPlanEntitlementDriver({
+ verifyEligibility: async () => false,
+ ineligibilityGraceDuration: { hours: 7 * 24 },
+ }),
+ });
+
+ await reverifyUserClaimedPlanEntitlements({
+ usersRepository,
+ planEntitlementsRepository,
+ planEntitlementDefinitionRegistry,
+ clock,
+ });
+
+ const { planEntitlements } = await planEntitlementsRepository.getUserPlanEntitlements({
+ userId: 'usr_1',
+ });
+
+ expect(planEntitlements[0]?.expiresAt).to.eql(new Date('2026-06-08T12:00:00Z'));
+ expect(planEntitlements[0]?.lastVerifiedAt).to.eql(new Date('2026-06-01T12:00:00Z'));
+ });
+
+ test('the ineligibility grace period never extends an entitlement that already expires sooner', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'usr_1', email: '[email protected]' }],
+ planEntitlements: [
+ {
+ id: 'pla_ent_aaaaaaaaaaaaaaaaaaaaaaaa',
+ userId: 'usr_1',
+ type: 'selfhst-premium',
+ source: 'user-claim',
+ grantedAt: new Date('2026-05-01T00:00:00Z'),
+ expiresAt: new Date('2026-06-03T00:00:00Z'),
+ lastVerifiedAt: new Date('2026-05-01T00:00:00Z'),
+ },
+ ],
+ });
+ const { clock } = createTestClock({ now: Temporal.Instant.from('2026-06-01T12:00:00Z') });
+
+ const usersRepository = createUsersRepository({ db });
+ const planEntitlementsRepository = createPlanEntitlementsRepository({ db, clock });
+ const planEntitlementDefinitionRegistry = createTestPlanEntitlementRegistry({
+ driver: createTestPlanEntitlementDriver({
+ verifyEligibility: async () => false,
+ ineligibilityGraceDuration: { hours: 7 * 24 },
+ }),
+ });
+
+ await reverifyUserClaimedPlanEntitlements({
+ usersRepository,
+ planEntitlementsRepository,
+ planEntitlementDefinitionRegistry,
+ clock,
+ });
+
+ const { planEntitlements } = await planEntitlementsRepository.getUserPlanEntitlements({
+ userId: 'usr_1',
+ });
+
+ expect(planEntitlements[0]?.expiresAt).to.eql(new Date('2026-06-03T00:00:00Z'));
+ expect(planEntitlements[0]?.lastVerifiedAt).to.eql(new Date('2026-05-01T00:00:00Z'));
+ });
+
+ test('when the eligibility verification fails, the entitlement is left untouched to be retried on the next run', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'usr_1', email: '[email protected]' }],
+ planEntitlements: [
+ {
+ id: 'pla_ent_aaaaaaaaaaaaaaaaaaaaaaaa',
+ userId: 'usr_1',
+ type: 'selfhst-premium',
+ source: 'user-claim',
+ grantedAt: new Date('2026-05-01T00:00:00Z'),
+ expiresAt: new Date('2026-06-10T00:00:00Z'),
+ lastVerifiedAt: new Date('2026-05-01T00:00:00Z'),
+ },
+ ],
+ });
+ const { clock } = createTestClock({ now: Temporal.Instant.from('2026-06-01T12:00:00Z') });
+
+ const usersRepository = createUsersRepository({ db });
+ const planEntitlementsRepository = createPlanEntitlementsRepository({ db, clock });
+ const planEntitlementDefinitionRegistry = createTestPlanEntitlementRegistry({
+ driver: createTestPlanEntitlementDriver({
+ verifyEligibility: async () => {
+ throw new Error('Verification endpoint unavailable');
+ },
+ }),
+ });
+
+ await reverifyUserClaimedPlanEntitlements({
+ usersRepository,
+ planEntitlementsRepository,
+ planEntitlementDefinitionRegistry,
+ clock,
+ });
+
+ const { planEntitlements } = await planEntitlementsRepository.getUserPlanEntitlements({
+ userId: 'usr_1',
+ });
+
+ expect(planEntitlements[0]?.expiresAt).to.eql(new Date('2026-06-10T00:00:00Z'));
+ expect(planEntitlements[0]?.lastVerifiedAt).to.eql(new Date('2026-05-01T00:00:00Z'));
+ });
+
+ test('admin-granted and already-expired entitlements are not re-verified', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [
+ { id: 'usr_1', email: '[email protected]' },
+ { id: 'usr_2', email: '[email protected]' },
+ ],
+ planEntitlements: [
+ {
+ id: 'pla_ent_aaaaaaaaaaaaaaaaaaaaaaaa',
+ userId: 'usr_1',
+ type: 'selfhst-premium',
+ source: 'admin',
+ grantedAt: new Date('2026-05-01T00:00:00Z'),
+ expiresAt: new Date('2026-06-10T00:00:00Z'),
+ },
+ {
+ id: 'pla_ent_bbbbbbbbbbbbbbbbbbbbbbbb',
+ userId: 'usr_2',
+ type: 'selfhst-premium',
+ source: 'user-claim',
+ grantedAt: new Date('2026-04-01T00:00:00Z'),
+ expiresAt: new Date('2026-05-01T00:00:00Z'),
+ },
+ ],
+ });
+ const { clock } = createTestClock({ now: Temporal.Instant.from('2026-06-01T12:00:00Z') });
+
+ const verifiedUserIds: string[] = [];
+ const usersRepository = createUsersRepository({ db });
+ const planEntitlementsRepository = createPlanEntitlementsRepository({ db, clock });
+ const planEntitlementDefinitionRegistry = createTestPlanEntitlementRegistry({
+ driver: createTestPlanEntitlementDriver({
+ verifyEligibility: async ({ user }) => {
+ verifiedUserIds.push(user.id);
+ return true;
+ },
+ }),
+ });
+
+ await reverifyUserClaimedPlanEntitlements({
+ usersRepository,
+ planEntitlementsRepository,
+ planEntitlementDefinitionRegistry,
+ clock,
+ });
+
+ expect(verifiedUserIds).to.eql([]);
+ });
+
+ test('a failure while re-verifying one entitlement does not prevent the re-verification of the others', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [
+ { id: 'usr_1', email: '[email protected]' },
+ { id: 'usr_2', email: '[email protected]' },
+ ],
+ planEntitlements: [
+ {
+ id: 'pla_ent_aaaaaaaaaaaaaaaaaaaaaaaa',
+ userId: 'usr_1',
+ type: 'selfhst-premium',
+ source: 'user-claim',
+ grantedAt: new Date('2026-05-01T00:00:00Z'),
+ expiresAt: new Date('2026-06-10T00:00:00Z'),
+ },
+ {
+ id: 'pla_ent_bbbbbbbbbbbbbbbbbbbbbbbb',
+ userId: 'usr_2',
+ type: 'selfhst-premium',
+ source: 'user-claim',
+ grantedAt: new Date('2026-05-01T00:00:00Z'),
+ expiresAt: new Date('2026-06-10T00:00:00Z'),
+ },
+ ],
+ });
+ const { clock } = createTestClock({ now: Temporal.Instant.from('2026-06-01T12:00:00Z') });
+
+ const baseUsersRepository = createUsersRepository({ db });
+ const usersRepository = {
+ ...baseUsersRepository,
+ getUserByIdOrThrow: async (args: { userId: string }) => {
+ if (args.userId === 'usr_1') {
+ throw new Error('Transient database error');
+ }
+ return baseUsersRepository.getUserByIdOrThrow(args);
+ },
+ };
+ const planEntitlementsRepository = createPlanEntitlementsRepository({ db, clock });
+ const planEntitlementDefinitionRegistry = createTestPlanEntitlementRegistry({
+ driver: createTestPlanEntitlementDriver({
+ verifyEligibility: async () => true,
+ claimValidityDuration: { hours: 10 * 24 },
+ }),
+ });
+
+ await reverifyUserClaimedPlanEntitlements({
+ usersRepository,
+ planEntitlementsRepository,
+ planEntitlementDefinitionRegistry,
+ clock,
+ });
+
+ const { planEntitlements: user1Entitlements } =
+ await planEntitlementsRepository.getUserPlanEntitlements({ userId: 'usr_1' });
+ const { planEntitlements: user2Entitlements } =
+ await planEntitlementsRepository.getUserPlanEntitlements({ userId: 'usr_2' });
+
+ expect(user1Entitlements[0]?.expiresAt).to.eql(new Date('2026-06-10T00:00:00Z'));
+ expect(user2Entitlements[0]?.expiresAt).to.eql(new Date('2026-06-11T12:00:00Z'));
+ });
+ });
});
diff --git a/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.usecases.ts b/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.usecases.ts
index f5cdfcc7..17042b6f 100644
--- a/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.usecases.ts
+++ b/apps/papra-server/src/modules/plan-entitlements/plan-entitlements.usecases.ts
@@ -1,10 +1,15 @@
import type { Logger } from '@crowlog/logger';
+import { safely } from '@corentinth/chisels';
import type { PlanId } from '../plans/plans.constants';
import { systemClock } from '../shared/clock/clock';
import type { Clock } from '../shared/clock/clock.types';
import { isNil } from '../shared/utils';
+import type { UsersRepository } from '../users/users.repository';
import type { PlanEntitlementSource } from './plan-entitlements.constants';
+import { PLAN_ENTITLEMENT_SOURCES } from './plan-entitlements.constants';
import {
+ createPlanEntitlementAlreadyExistsError,
+ createPlanEntitlementClaimsNotEnabledError,
createPlanEntitlementNotEligibleError,
createPlanEntitlementUnknownTypeError,
} from './plan-entitlements.errors';
@@ -20,6 +25,7 @@ export async function grantUserPlanEntitlement({
type,
source,
expiresAt,
+ usersRepository,
planEntitlementsRepository,
planEntitlementDefinitionRegistry,
clock = systemClock,
@@ -28,6 +34,7 @@ export async function grantUserPlanEntitlement({
type: PlanEntitlementType;
source: PlanEntitlementSource;
expiresAt?: Date | null;
+ usersRepository: UsersRepository;
planEntitlementsRepository: PlanEntitlementsRepository;
planEntitlementDefinitionRegistry: PlanEntitlementDefinitionRegistry;
clock?: Clock;
@@ -40,23 +47,207 @@ export async function grantUserPlanEntitlement({
throw createPlanEntitlementUnknownTypeError();
}
- const isEligible = await planEntitlementDriver.verifyEligibility({ userId });
+ const now = new Date(clock.now().epochMilliseconds);
+
+ // Checked before verifying the eligibility to avoid a pointless call to the
+ // driver's external verification service when the user is already entitled
+ const { planEntitlement: existingPlanEntitlement } =
+ await planEntitlementsRepository.getUserPlanEntitlementByType({ userId, type });
+
+ const isExistingPlanEntitlementActive =
+ existingPlanEntitlement &&
+ (existingPlanEntitlement.expiresAt === null || existingPlanEntitlement.expiresAt > now);
+
+ if (isExistingPlanEntitlementActive) {
+ throw createPlanEntitlementAlreadyExistsError();
+ }
+
+ const { user } = await usersRepository.getUserByIdOrThrow({ userId });
+
+ const isEligible = await planEntitlementDriver.verifyEligibility({ user });
if (!isEligible) {
throw createPlanEntitlementNotEligibleError();
}
+ if (existingPlanEntitlement) {
+ // An expired entitlement of the same type is re-activated in place, as the
+ // unique (userId, type) index prevents inserting a new row
+ const { planEntitlement } = await planEntitlementsRepository.updatePlanEntitlement({
+ planEntitlementId: existingPlanEntitlement.id,
+ expiresAt: expiresAt ?? null,
+ lastVerifiedAt: now,
+ source,
+ grantedAt: now,
+ });
+
+ return { planEntitlement };
+ }
+
const { planEntitlement } = await planEntitlementsRepository.createPlanEntitlement({
userId,
type,
source,
expiresAt,
- lastVerifiedAt: new Date(clock.now().epochMilliseconds),
+ lastVerifiedAt: now,
});
return { planEntitlement };
}
+export async function claimUserPlanEntitlement({
+ userId,
+ type,
+ usersRepository,
+ planEntitlementsRepository,
+ planEntitlementDefinitionRegistry,
+ clock = systemClock,
+}: {
+ userId: string;
+ type: PlanEntitlementType;
+ usersRepository: UsersRepository;
+ planEntitlementsRepository: PlanEntitlementsRepository;
+ planEntitlementDefinitionRegistry: PlanEntitlementDefinitionRegistry;
+ clock?: Clock;
+}) {
+ const { planEntitlementDriver } = planEntitlementDefinitionRegistry.getPlanEntitlementDriver({
+ type,
+ });
+
+ if (isNil(planEntitlementDriver)) {
+ throw createPlanEntitlementUnknownTypeError();
+ }
+
+ const isEnabledForNewClaims = await planEntitlementDriver.getIsEnabledForNewClaims();
+
+ if (!isEnabledForNewClaims) {
+ throw createPlanEntitlementClaimsNotEnabledError();
+ }
+
+ const expiresAt = new Date(
+ clock.now().add(planEntitlementDriver.claimValidityDuration).epochMilliseconds,
+ );
+
+ return grantUserPlanEntitlement({
+ userId,
+ type,
+ source: PLAN_ENTITLEMENT_SOURCES.USER_CLAIM,
+ expiresAt,
+ usersRepository,
+ planEntitlementsRepository,
+ planEntitlementDefinitionRegistry,
+ clock,
+ });
+}
+
+export async function reverifyUserClaimedPlanEntitlements({
+ usersRepository,
+ planEntitlementsRepository,
+ planEntitlementDefinitionRegistry,
+ clock = systemClock,
+ logger = createLogger({ namespace: 'reverifyUserClaimedPlanEntitlements' }),
+}: {
+ usersRepository: UsersRepository;
+ planEntitlementsRepository: PlanEntitlementsRepository;
+ planEntitlementDefinitionRegistry: PlanEntitlementDefinitionRegistry;
+ clock?: Clock;
+ logger?: Logger;
+}) {
+ const { planEntitlements } = await planEntitlementsRepository.getActiveUserClaimedEntitlements();
+
+ for (const planEntitlement of planEntitlements) {
+ // A failure on one entitlement must not prevent the re-verification of the
+ // others, it will be retried on the next run and only lapses at its expiresAt
+ const [, reverificationError] = await safely(
+ reverifyUserClaimedPlanEntitlement({
+ planEntitlement,
+ usersRepository,
+ planEntitlementsRepository,
+ planEntitlementDefinitionRegistry,
+ clock,
+ logger,
+ }),
+ );
+
+ if (reverificationError) {
+ logger.error(
+ { planEntitlementId: planEntitlement.id, error: reverificationError },
+ 'Failed to re-verify plan entitlement',
+ );
+ }
+ }
+}
+
+async function reverifyUserClaimedPlanEntitlement({
+ planEntitlement,
+ usersRepository,
+ planEntitlementsRepository,
+ planEntitlementDefinitionRegistry,
+ clock,
+ logger,
+}: {
+ planEntitlement: {
+ id: string;
+ userId: string;
+ type: PlanEntitlementType;
+ expiresAt: Date | null;
+ };
+ usersRepository: UsersRepository;
+ planEntitlementsRepository: PlanEntitlementsRepository;
+ planEntitlementDefinitionRegistry: PlanEntitlementDefinitionRegistry;
+ clock: Clock;
+ logger: Logger;
+}) {
+ const { id: planEntitlementId, userId, type } = planEntitlement;
+
+ const { planEntitlementDriver } = planEntitlementDefinitionRegistry.getPlanEntitlementDriver({
+ type,
+ });
+
+ if (isNil(planEntitlementDriver)) {
+ logger.error({ planEntitlementId, type }, 'No plan entitlement driver found for type');
+ return;
+ }
+
+ const { user } = await usersRepository.getUserByIdOrThrow({ userId });
+
+ const isEligible = await planEntitlementDriver.verifyEligibility({ user });
+
+ if (!isEligible) {
+ const now = clock.now();
+ const graceExpiresAt = new Date(
+ now.add(planEntitlementDriver.ineligibilityGraceDuration).epochMilliseconds,
+ );
+
+ // Cap the expiration to the grace period, but never extend an entitlement
+ // that already expires sooner
+ const shouldCapExpiration =
+ planEntitlement.expiresAt === null || planEntitlement.expiresAt > graceExpiresAt;
+
+ if (shouldCapExpiration) {
+ await planEntitlementsRepository.updatePlanEntitlement({
+ planEntitlementId,
+ expiresAt: graceExpiresAt,
+ lastVerifiedAt: new Date(now.epochMilliseconds),
+ });
+ }
+
+ logger.info(
+ { planEntitlementId, type },
+ 'User is no longer eligible for plan entitlement, expiration capped to the grace period',
+ );
+ return;
+ }
+
+ const now = clock.now();
+
+ await planEntitlementsRepository.updatePlanEntitlement({
+ planEntitlementId,
+ expiresAt: new Date(now.add(planEntitlementDriver.claimValidityDuration).epochMilliseconds),
+ lastVerifiedAt: new Date(now.epochMilliseconds),
+ });
+}
+
export async function resolveOrganizationPlanEntitlements({
organizationId,
planEntitlementsRepository,
diff --git a/apps/papra-server/src/modules/plan-entitlements/selfhst/selfhst.plan-entitlements.config.ts b/apps/papra-server/src/modules/plan-entitlements/selfhst/selfhst.plan-entitlements.config.ts
index f0ce3048..c94e5ec5 100644
--- a/apps/papra-server/src/modules/plan-entitlements/selfhst/selfhst.plan-entitlements.config.ts
+++ b/apps/papra-server/src/modules/plan-entitlements/selfhst/selfhst.plan-entitlements.config.ts
@@ -1,5 +1,6 @@
-import { booleanishSchema } from '../../config/config.schemas';
+import { booleanishSchema, urlSchema } from '../../config/config.schemas';
import type { AppConfigDefinition } from '../../config/config.types';
+import * as v from 'valibot';
export const selfhstEntitlementsConfig = {
isEnabledForNewClaims: {
@@ -7,5 +8,22 @@ export const selfhstEntitlementsConfig = {
schema: booleanishSchema,
default: true,
env: 'SELFHST_ENTITLEMENTS_IS_ENABLED_FOR_NEW_CLAIMS',
+ showInDocumentation: false,
+ },
+ entitlementVerification: {
+ endpoint: {
+ doc: 'The endpoint to verify the selfhst entitlement.',
+ schema: v.optional(urlSchema),
+ default: undefined,
+ env: 'SELFHST_ENTITLEMENTS_VERIFICATION_ENDPOINT',
+ showInDocumentation: false,
+ },
+ token: {
+ doc: 'The bearer token to use for the selfhst entitlement verification endpoint.',
+ schema: v.optional(v.string()),
+ default: undefined,
+ env: 'SELFHST_ENTITLEMENTS_VERIFICATION_TOKEN',
+ showInDocumentation: false,
+ },
},
} as const satisfies AppConfigDefinition;
diff --git a/apps/papra-server/src/modules/plan-entitlements/selfhst/selfhst.plan-entitlements.constants.ts b/apps/papra-server/src/modules/plan-entitlements/selfhst/selfhst.plan-entitlements.constants.ts
index 15f3be50..6a66647d 100644
--- a/apps/papra-server/src/modules/plan-entitlements/selfhst/selfhst.plan-entitlements.constants.ts
+++ b/apps/papra-server/src/modules/plan-entitlements/selfhst/selfhst.plan-entitlements.constants.ts
@@ -1 +1,15 @@
export const SELFHST_ENTITLEMENT_NAME = 'selfhst-premium';
+
+// Validity window granted on claim and rolled forward by the periodic
+// re-verification task; a lapsed selfh.st subscription expires naturally.
+// Temporal.Instant does not support calendar units, hence hours.
+export const SELFHST_ENTITLEMENT_CLAIM_VALIDITY_DURATION: Temporal.DurationLike = {
+ hours: 45 * 24,
+};
+
+// Once selfh.st confirms a user is no longer premium, their entitlement
+// expiration is capped to this grace period instead of the full validity
+// window, long enough to absorb billing hiccups on selfh.st's side
+export const SELFHST_ENTITLEMENT_INELIGIBILITY_GRACE_DURATION: Temporal.DurationLike = {
+ hours: 7 * 24,
+};
diff --git a/apps/papra-server/src/modules/plan-entitlements/selfhst/selfhst.plan-entitlements.services.ts b/apps/papra-server/src/modules/plan-entitlements/selfhst/selfhst.plan-entitlements.services.ts
new file mode 100644
index 00000000..2c7b4770
--- /dev/null
+++ b/apps/papra-server/src/modules/plan-entitlements/selfhst/selfhst.plan-entitlements.services.ts
@@ -0,0 +1,68 @@
+import type { Logger } from '@crowlog/logger';
+import { ofetch } from 'ofetch';
+import * as v from 'valibot';
+import { createLogger } from '../../shared/logger/logger';
+import { IN_MS } from '../../shared/units';
+
+const verificationResponseSchema = v.object({
+ valid: v.boolean(),
+});
+
+export async function verifyEligibilityForSelfhstPlanEntitlements({
+ email,
+ endpointUrl,
+ token,
+ logger = createLogger({ namespace: 'selfhst.plan-entitlements' }),
+}: {
+ email: string;
+ endpointUrl?: string;
+ token?: string;
+ logger?: Logger;
+}): Promise<{ isValid: boolean }> {
+ if (!endpointUrl || !token) {
+ logger.warn('Selfhst entitlement verification endpoint or token is not configured.');
+ return { isValid: false };
+ }
+
+ const response = await ofetch.raw<unknown>(endpointUrl, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${token}`,
+ },
+ body: JSON.stringify({ email }),
+ ignoreResponseError: true,
+ timeout: 5 * IN_MS.SECOND,
+ });
+
+ if (!response.ok) {
+ logger.error(
+ {
+ status: response.status,
+ statusText: response.statusText,
+ },
+ 'Failed to verify eligibility for selfhst plan entitlements.',
+ );
+ return { isValid: false };
+ }
+
+ // The response body is already consumed and parsed by ofetch
+ const responseData = response._data;
+
+ const parsedResponse = v.safeParse(verificationResponseSchema, responseData);
+
+ if (!parsedResponse.success) {
+ logger.error(
+ {
+ responseData,
+ errors: parsedResponse.issues,
+ },
+ 'Failed to parse verification response for selfhst plan entitlements.',
+ );
+ return { isValid: false };
+ }
+
+ const { valid } = parsedResponse.output;
+
+ return { isValid: valid };
+}
diff --git a/apps/papra-server/src/modules/plan-entitlements/selfhst/selfhst.plan-entitlements.ts b/apps/papra-server/src/modules/plan-entitlements/selfhst/selfhst.plan-entitlements.ts
index b1cd5b5d..033835cb 100644
--- a/apps/papra-server/src/modules/plan-entitlements/selfhst/selfhst.plan-entitlements.ts
+++ b/apps/papra-server/src/modules/plan-entitlements/selfhst/selfhst.plan-entitlements.ts
@@ -1,12 +1,31 @@
import { PLAN_IDS } from '../../plans/plans.constants';
import type { PlanEntitlementDriverFactory } from '../plan-entitlements.types';
+import {
+ SELFHST_ENTITLEMENT_CLAIM_VALIDITY_DURATION,
+ SELFHST_ENTITLEMENT_INELIGIBILITY_GRACE_DURATION,
+} from './selfhst.plan-entitlements.constants';
+import { verifyEligibilityForSelfhstPlanEntitlements } from './selfhst.plan-entitlements.services';
export const selfhstPlanEntitlementsFactory: PlanEntitlementDriverFactory = ({ config }) => {
const selfhstConfig = config.planEntitlements.selfhst;
+ const { endpoint, token } = selfhstConfig.entitlementVerification;
return {
- getIsEnabledForNewClaims: async () => selfhstConfig.isEnabledForNewClaims,
- verifyEligibility: async () => false, // Temporary, waiting for implementation
+ // Without the verification endpoint configured, claims would always be
+ // rejected as not-eligible, so report them as disabled instead
+ getIsEnabledForNewClaims: async () =>
+ selfhstConfig.isEnabledForNewClaims && Boolean(endpoint) && Boolean(token),
+ verifyEligibility: async ({ user }) => {
+ const { isValid } = await verifyEligibilityForSelfhstPlanEntitlements({
+ email: user.email,
+ endpointUrl: endpoint,
+ token,
+ });
+
+ return isValid;
+ },
planId: PLAN_IDS.FREE_EXTENDED,
+ claimValidityDuration: SELFHST_ENTITLEMENT_CLAIM_VALIDITY_DURATION,
+ ineligibilityGraceDuration: SELFHST_ENTITLEMENT_INELIGIBILITY_GRACE_DURATION,
};
};
diff --git a/apps/papra-server/src/modules/plan-entitlements/tasks/reverify-plan-entitlements.task.ts b/apps/papra-server/src/modules/plan-entitlements/tasks/reverify-plan-entitlements.task.ts
new file mode 100644
index 00000000..377fa844
--- /dev/null
+++ b/apps/papra-server/src/modules/plan-entitlements/tasks/reverify-plan-entitlements.task.ts
@@ -0,0 +1,50 @@
+import type { Database } from '../../app/database/database.types';
+import type { Config } from '../../config/config.types';
+import type { PlanEntitlementDefinitionRegistry } from '../plan-entitlements.registry';
+import type { TaskServices } from '../../tasks/tasks.services';
+import { createLogger } from '../../shared/logger/logger';
+import { createUsersRepository } from '../../users/users.repository';
+import { createPlanEntitlementsRepository } from '../plan-entitlements.repository';
+import { reverifyUserClaimedPlanEntitlements } from '../plan-entitlements.usecases';
+
+const logger = createLogger({ namespace: 'plan-entitlements:tasks:reverifyPlanEntitlements' });
+
+export async function registerReverifyPlanEntitlementsTask({
+ taskServices,
+ db,
+ config,
+ planEntitlementDefinitionRegistry,
+}: {
+ taskServices: TaskServices;
+ db: Database;
+ config: Config;
+ planEntitlementDefinitionRegistry: PlanEntitlementDefinitionRegistry;
+}) {
+ const taskName = 'reverify-plan-entitlements';
+ const { cron, runOnStartup } = config.tasks.reverifyPlanEntitlements;
+
+ taskServices.registerTask({
+ taskName,
+ handler: async () => {
+ const usersRepository = createUsersRepository({ db });
+ const planEntitlementsRepository = createPlanEntitlementsRepository({ db });
+
+ await reverifyUserClaimedPlanEntitlements({
+ usersRepository,
+ planEntitlementsRepository,
+ planEntitlementDefinitionRegistry,
+ });
+
+ logger.info('Re-verified user-claimed plan entitlements');
+ },
+ });
+
+ await taskServices.schedulePeriodicJob({
+ scheduleId: `periodic-${taskName}`,
+ taskName,
+ cron,
+ immediate: runOnStartup,
+ });
+
+ logger.info({ taskName, cron, runOnStartup }, 'Re-verify plan entitlements task registered');
+}
diff --git a/apps/papra-server/src/modules/tasks/tasks.config.ts b/apps/papra-server/src/modules/tasks/tasks.config.ts
index 92705d5f..1647243c 100644
--- a/apps/papra-server/src/modules/tasks/tasks.config.ts
+++ b/apps/papra-server/src/modules/tasks/tasks.config.ts
@@ -119,4 +119,18 @@ export const tasksConfig = {
],
},
},
+ reverifyPlanEntitlements: {
+ cron: {
+ doc: 'The cron schedule for the task to re-verify user-claimed plan entitlements',
+ schema: v.string(),
+ default: '0 3 * * *',
+ env: 'PLAN_ENTITLEMENTS_REVERIFY_CRON',
+ },
+ runOnStartup: {
+ doc: 'Whether the task to re-verify user-claimed plan entitlements should run on startup',
+ schema: booleanishSchema,
+ default: false,
+ env: ['PLAN_ENTITLEMENTS_REVERIFY_RUN_ON_STARTUP', RUN_ALL_SCHEDULED_TASKS_ON_STARTUP_ENV],
+ },
+ },
} as const satisfies ConfigDefinition;
diff --git a/apps/papra-server/src/modules/tasks/tasks.definitions.ts b/apps/papra-server/src/modules/tasks/tasks.definitions.ts
index db8c61bf..ce9daee0 100644
--- a/apps/papra-server/src/modules/tasks/tasks.definitions.ts
+++ b/apps/papra-server/src/modules/tasks/tasks.definitions.ts
@@ -5,6 +5,7 @@ import { registerHardDeleteExpiredDocumentsTask } from '../documents/tasks/hard-
import { registerPurgeExpiredKvEntriesTask } from '../kv-store/tasks/purge-expired-kv-entries.task';
import { registerExpireInvitationsTask } from '../organizations/tasks/expire-invitations.task';
import { registerPurgeExpiredOrganizationsTask } from '../organizations/tasks/purge-expired-organizations.task';
+import { registerReverifyPlanEntitlementsTask } from '../plan-entitlements/tasks/reverify-plan-entitlements.task';
import { registerApplyTaggingRuleToDocumentsTask } from '../tagging-rules/tasks/apply-tagging-rule-to-documents.task';
export async function registerTaskDefinitions(deps: GlobalDependencies) {
@@ -15,4 +16,5 @@ export async function registerTaskDefinitions(deps: GlobalDependencies) {
await registerApplyTaggingRuleToDocumentsTask(deps);
await registerPurgeExpiredKvEntriesTask(deps);
await registerAutoTagDocumentTask(deps);
+ await registerReverifyPlanEntitlementsTask(deps);
}