Skip to content

Gift links: service & admin API - #28627

Closed
jonatansberg wants to merge 1 commit into
mainfrom
ber-3727-gift-links-service-admin-api
Closed

jonatansberg wants to merge 1 commit into
mainfrom
ber-3727-gift-links-service-admin-api

Conversation

@jonatansberg

Copy link
Copy Markdown
Member

Slice 2 of 4 carving up the gift-links spike (#28625). Stacked on #28626 (BER-3726, data foundation) — review/merge that first.

ref https://linear.app/ghost/issue/BER-3727

What this adds

  • GiftLinksService (services/gift-links): token generation, ensure/reset/resetAll/getActive/getActiveByToken/recordRead, transaction-safe with forUpdate post locking; wired into boot initServices.
  • Admin API (api/endpoints/gift-links.js + output serializer + routes): read, ensure, reset, reset_all endpoints, all gated behind the giftLinks private flag.

Reset-eligibility fix

The reset endpoint now uses the lenient "post exists" check (findPostOrThrow) instead of validateEligiblePost. A publisher must be able to rotate a leaked link even after the post became ineligible (flipped to public or unpublished) — otherwise the leaked link can't be invalidated. ensure still requires eligibility. Added an e2e test covering: mint on a members-only post → flip to public → ensure 422s but reset succeeds.

Tests

  • unit: 3 passing
  • integration: 14 passing
  • e2e-api admin gift-links: 18 passing
  • admin config snapshot: updated for the giftLinks labs flag, passing

Everything is behind the off-by-default giftLinks flag.

@coderabbitai

coderabbitai Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 5e64ba9f-0579-4b86-a95b-4ad790403c7f

📥 Commits

Reviewing files that changed from the base of the PR and between 3332e19 and 90ac687.

📒 Files selected for processing (14)
  • ghost/core/core/boot.js
  • ghost/core/core/server/api/endpoints/gift-links.ts
  • ghost/core/core/server/api/endpoints/index.js
  • ghost/core/core/server/api/endpoints/utils/serializers/output/gift-links.ts
  • ghost/core/core/server/api/endpoints/utils/serializers/output/index.js
  • ghost/core/core/server/services/gift-links/gift-link-bookshelf-repository.ts
  • ghost/core/core/server/services/gift-links/gift-link-repository.ts
  • ghost/core/core/server/services/gift-links/gift-link.ts
  • ghost/core/core/server/services/gift-links/gift-links-service.ts
  • ghost/core/core/server/services/gift-links/index.ts
  • ghost/core/core/server/web/api/endpoints/admin/routes.js
  • ghost/core/test/e2e-api/admin/gift-links.test.ts
  • ghost/core/test/integration/services/gift-links.test.ts
  • ghost/core/test/unit/server/services/gift-links/gift-links-service.test.ts
🚧 Files skipped from review as they are similar to previous changes (10)
  • ghost/core/core/server/api/endpoints/utils/serializers/output/index.js
  • ghost/core/core/boot.js
  • ghost/core/core/server/services/gift-links/gift-link.ts
  • ghost/core/core/server/web/api/endpoints/admin/routes.js
  • ghost/core/core/server/api/endpoints/utils/serializers/output/gift-links.ts
  • ghost/core/core/server/services/gift-links/gift-link-repository.ts
  • ghost/core/test/integration/services/gift-links.test.ts
  • ghost/core/test/e2e-api/admin/gift-links.test.ts
  • ghost/core/core/server/services/gift-links/gift-link-bookshelf-repository.ts
  • ghost/core/core/server/api/endpoints/gift-links.ts

Walkthrough

This PR introduces a gift links feature for Ghost. A new GiftLink domain type and GiftLinkRepository interface define the persistence boundary. A GiftLinkBookshelfRepository implements database access via knex/Bookshelf, handling row conversion, active-link queries, transactional creation, and atomic read-counter updates. GiftLinksService provides cryptographic token generation, idempotent upsert, transactional reset, site-wide resetAll, and read-recording methods. A GiftLinksServiceWrapper defers model loading and is initialized in the boot sequence. Four admin API endpoints (read, upsert, reset, resetAll) enforce authorization via assertCanManageGiftLink and delegate to the service. An output serializer normalizes GiftLink responses, and the endpoints are registered behind a giftLinks lab flag in the admin routes. Unit, integration, and e2e tests cover token generation, all service operations, endpoint behavior, and role-based access control.

Possibly related PRs

  • TryGhost/Ghost#28626: Creates the gift_links database table and Bookshelf model, the giftLinks lab flag, and gift_link permissions that this PR's service and API endpoints depend on directly.
  • TryGhost/Ghost#28669: Adds the "Manage gift links" permission to the "Admin Integration" role, providing the authorization foundation for the per-post manage.gift_link(id) permission checks used throughout this PR's API controller.

Suggested reviewers

  • kevinansfield
  • 9larsons
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The PR title 'Gift links: service & admin API' directly summarizes the main changes—implementation of the GiftLinksService and admin API endpoints for gift links.
Description check ✅ Passed The PR description is well-organized and directly related to the changeset, detailing the service implementation, admin API endpoints, reset-eligibility fix, and test coverage.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ber-3727-gift-links-service-admin-api

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@nx-cloud

nx-cloud Bot commented Jun 16, 2026 •

Copy link
Copy Markdown

🤖 Nx Cloud AI Fix

Ensure the fix-ci command is configured to always run in your CI pipeline to get automatic fixes in future runs. For more information, please see https://nx.dev/ci/features/self-healing-ci


View your CI Pipeline Execution ↗ for commit 90ac687

Command Status Duration Result
nx build @tryghost/signup-form ✅ Succeeded <1s View ↗
nx run ghost:test:ci:integration:no-coverage ✅ Succeeded 2m 1s View ↗
nx run ghost:test:ci:integration ✅ Succeeded 1m 21s View ↗
nx run ghost:test:ci:e2e:no-coverage ✅ Succeeded 4m 12s View ↗
nx run ghost:test:ci:e2e ✅ Succeeded 4m 10s View ↗
nx run ghost:test:ci:legacy ✅ Succeeded 2m 17s View ↗
nx build @tryghost/sodo-search ✅ Succeeded <1s View ↗
nx build @tryghost/activitypub ✅ Succeeded 3s View ↗
Additional runs (10) ✅ Succeeded ... View ↗

💡 Verify your cache is correct by running tasks in a sandbox. Read docs ↗


☁️ Nx Cloud last updated this comment at 2026-06-17 14:30:15 UTC

@jonatansberg
jonatansberg force-pushed the ber-3726-gift-links-data-foundation branch from 9a064db to 9ed7a1d Compare June 16, 2026 14:30
@jonatansberg
jonatansberg force-pushed the ber-3727-gift-links-service-admin-api branch from bca071c to 27420ed Compare June 16, 2026 14:30
@jonatansberg
jonatansberg force-pushed the ber-3726-gift-links-data-foundation branch from 9ed7a1d to 4ba013d Compare June 16, 2026 14:39
@jonatansberg
jonatansberg force-pushed the ber-3727-gift-links-service-admin-api branch from 27420ed to d85e91e Compare June 16, 2026 14:39
Base automatically changed from ber-3726-gift-links-data-foundation to main June 16, 2026 14:59
@jonatansberg
jonatansberg force-pushed the ber-3727-gift-links-service-admin-api branch from d85e91e to 05de009 Compare June 17, 2026 06:31
@jonatansberg
jonatansberg force-pushed the ber-3727-gift-links-service-admin-api branch from 05de009 to 61115dc Compare June 17, 2026 06:52
@jonatansberg
jonatansberg marked this pull request as ready for review June 17, 2026 07:11

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@ghost/core/core/server/api/endpoints/gift-links.js`:
- Around line 124-127: Move the validateEligiblePost call from line 124 into the
same locked transaction as giftLinks.api.ensure to prevent a race condition
where the post's visibility or status could change between validation and link
creation. The eligibility check must execute atomically with the ensure
operation so that an ineligible post cannot have a gift link created for it,
maintaining the 422 contract of the ensure method. Refactor to validate
eligibility within the service transaction that already locks the post for the
ensure call.

In `@ghost/core/test/e2e-api/admin/gift-links.test.js`:
- Around line 154-169: The fixture restoration code that calls models.Post.edit
with visibility 'members' is only executed if all assertions pass, but the
earlier models.Post.edit that changes visibility to 'public' could cause test
assertions to fail, skipping the restoration and leaving the fixture in a broken
state for subsequent tests. Wrap the mutation and test logic (from the first
models.Post.edit call through the assertions) in a try block and move the
fixture restoration models.Post.edit call into a finally block to ensure the
post visibility is always restored to 'members' regardless of whether assertions
throw errors.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 69a4d752-6d71-4b72-8eac-4a596b6182b4

📥 Commits

Reviewing files that changed from the base of the PR and between 337cac4 and 61115dc.

📒 Files selected for processing (11)
  • ghost/core/core/boot.js
  • ghost/core/core/server/api/endpoints/gift-links.js
  • ghost/core/core/server/api/endpoints/index.js
  • ghost/core/core/server/api/endpoints/utils/serializers/output/gift-links.js
  • ghost/core/core/server/api/endpoints/utils/serializers/output/index.js
  • ghost/core/core/server/services/gift-links/gift-links-service.js
  • ghost/core/core/server/services/gift-links/index.js
  • ghost/core/core/server/web/api/endpoints/admin/routes.js
  • ghost/core/test/e2e-api/admin/gift-links.test.js
  • ghost/core/test/integration/services/gift-links.test.js
  • ghost/core/test/unit/server/services/gift-links/gift-links-service.test.js

@rob-ghost rob-ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we convert new files to TypeScript?

@rob-ghost rob-ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some overall questions and suggestions about the shape of this.

I think the permissions middleware is pushing repository concerns into the API when it should be generic middleware.

I think the service is encapsulating both domain logic/invariants and repository concerns, leaning on bookshelf is reducing type-ability and test-ability and we can maybe leverage a repository inverted interface to clean this up.

I think there's coupling and constraints (posts & gift link relations) being handled in the service layer that might already be better modelled in the data layer.

Comment on lines +83 to +105
return this.withTransaction(options, async (opts) => {
// Lock the post row for the duration of the transaction. MySQL has
// no partial unique index, so this serialises concurrent
// ensure/reset for the same post and guarantees <=1 active link
// even on the very first ensure (when no row exists to lock).
// require:true also validates the post exists. `status: 'all'`
// bypasses the Post model's default published-only filter so the
// lock is eligibility-agnostic (eligibility is the API's concern).
await this.models.Post.findOne({id: postId, status: 'all'}, {...opts, forUpdate: true, require: true});

const existing = await this.models.GiftLink.findOne(
{post_id: postId, status: 'active'},
{...opts, require: false}
);
if (existing) {
return existing;
}

return this.models.GiftLink.add({
post_id: postId,
token: this.generateToken()
}, opts);
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question: Is it necessary to interact with posts separate to gift links? If the relations are setup properly in the database, wouldn't the foreign key constraints work in our favour here so we can just upsert on GiftLink?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Partly — we removed the post-row write-lock (it coupled every gift write to a posts-table lock, contending with post edits) and now lean on the post_id FK as the integrity backstop, with a small repo-encapsulated postExists only for a clean 404. We deliberately did not add a unique constraint / upsert-on-conflict: <=1 active per post is kept SOFT because history retention rules out a cheap partial-unique index (MySQL has none) and no consumer needs a hard guarantee. Concurrent duplicates converge via a post-commit "keep most-recent, deactivate the rest" sweep. Leaving this open in case you'd prefer a stricter (DB-enforced) approach — happy to discuss.

@jonatansberg
jonatansberg force-pushed the ber-3727-gift-links-service-admin-api branch from 61115dc to 1b0362f Compare June 17, 2026 09:28
@jonatansberg
jonatansberg requested a review from rob-ghost June 17, 2026 09:30

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
ghost/core/core/server/api/endpoints/gift-links.ts (1)

64-68: ⚡ Quick win

Align the eligibility docblock with the implemented reset behavior.

This comment still says eligibility is enforced for both create and reset, but reset intentionally uses the lenient existence-only path. Updating the wording avoids future confusion during maintenance.

✏️ Suggested doc update
- * Eligibility is enforced here (the API layer), not in the service: a gift link
- * may only be CREATED/RESET for a published, gated (non-public) post or page.
+ * Eligibility is enforced here (the API layer), not in the service: a gift link
+ * may only be CREATED for a published, gated (non-public) post or page.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ghost/core/core/server/api/endpoints/gift-links.ts` around lines 64 - 68, The
docblock comment describing eligibility enforcement is inaccurate regarding the
reset operation. Currently it states that eligibility is enforced for both
CREATED and RESET operations, but the reset method actually uses the lenient
path that only checks for post existence, similar to the read operation. Update
the docblock comment to clarify that strict eligibility enforcement (published,
gated post or page requirement) applies only to the CREATE operation, while the
RESET operation intentionally follows the lenient path that only requires the
post to exist, allowing publishers to inspect or reset links on posts that
became ineligible.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@ghost/core/core/server/api/endpoints/gift-links.ts`:
- Around line 64-68: The docblock comment describing eligibility enforcement is
inaccurate regarding the reset operation. Currently it states that eligibility
is enforced for both CREATED and RESET operations, but the reset method actually
uses the lenient path that only checks for post existence, similar to the read
operation. Update the docblock comment to clarify that strict eligibility
enforcement (published, gated post or page requirement) applies only to the
CREATE operation, while the RESET operation intentionally follows the lenient
path that only requires the post to exist, allowing publishers to inspect or
reset links on posts that became ineligible.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c2b6cab1-bf71-42e9-9dde-9ce917dfd641

📥 Commits

Reviewing files that changed from the base of the PR and between 61115dc and 1b0362f.

📒 Files selected for processing (11)
  • ghost/core/core/boot.js
  • ghost/core/core/server/api/endpoints/gift-links.ts
  • ghost/core/core/server/api/endpoints/index.js
  • ghost/core/core/server/api/endpoints/utils/serializers/output/gift-links.ts
  • ghost/core/core/server/api/endpoints/utils/serializers/output/index.js
  • ghost/core/core/server/services/gift-links/gift-links-service.ts
  • ghost/core/core/server/services/gift-links/index.ts
  • ghost/core/core/server/web/api/endpoints/admin/routes.js
  • ghost/core/test/e2e-api/admin/gift-links.test.ts
  • ghost/core/test/integration/services/gift-links.test.ts
  • ghost/core/test/unit/server/services/gift-links/gift-links-service.test.ts
✅ Files skipped from review due to trivial changes (3)
  • ghost/core/test/unit/server/services/gift-links/gift-links-service.test.ts
  • ghost/core/test/e2e-api/admin/gift-links.test.ts
  • ghost/core/core/server/services/gift-links/index.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • ghost/core/core/server/api/endpoints/utils/serializers/output/index.js
  • ghost/core/core/server/web/api/endpoints/admin/routes.js
  • ghost/core/core/boot.js

@rob-ghost rob-ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the conversion of typescript has shown some areas we can improve in terms of abstracting away bookshelf so we don't have to deal with it and improve typing and testability, along with the comments of the last review.

@jonatansberg
jonatansberg force-pushed the ber-3727-gift-links-service-admin-api branch from 1b0362f to 3332e19 Compare June 17, 2026 13:25
@jonatansberg

jonatansberg commented Jun 17, 2026 •

Copy link
Copy Markdown
Member Author

Thanks for the thorough review — this was a substantial reshape, so a quick map (each thread replied to inline):

Repository + domain model (Rob). Added a GiftLink domain type, a GiftLinkRepository interface and a GiftLinkBookshelfRepository impl, modelled on the sibling gifts/ service. The service is injected with the repository and returns plain domain objects — Bookshelf is gone from the service/API/serializer. Reads/sweeps use knex; the model layer is used only for create (ObjectId/created_at generation).

Eligibility removed. Create-time eligibility (published/gated) is dropped — the reader path already gates redemption via the public content API (published-only), so it was advisory UX, not a security control. This also dissolves CodeRabbit's TOCTOU finding.

Permissions. Moved to an async permissions(frame) hook (à la users.js transferOwnership), carrying both the gift_link: manage capability gate and the edit.post ownership check.

API shape (Kevin). Nested: GET|PUT /posts/:id/gift_link + POST /posts/:id/gift_link/reset (with /pages parallels); verbs flipped (PUT for the idempotent upsert, POST for reset); ensure → upsert; giftLinks.api → giftLinks.service.

Concurrency. The <=1 active per post invariant is deliberately SOFT (no lock, no unique index — history retention rules out a cheap partial-unique, and no consumer needs a hard guarantee). A post-commit "keep most-recent, deactivate the rest" sweep converges concurrent duplicates as a single atomic statement, so it can't transiently zero out.

All gift-links suites (unit/integration/e2e + reader) are green and lint:types is clean; the reader (#28629) and admin UI (#28630) PRs are re-stacked on top.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@ghost/core/core/server/services/gift-links/gift-links-service.ts`:
- Around line 70-75: The deactivateAllButMostRecent method call on line 73 does
not pass the options parameter that is available in the upsert method scope.
This causes the sweep operation to execute outside any transaction context,
creating a race condition under concurrent calls. Pass the options parameter to
the deactivateAllButMostRecent call to maintain transaction consistency, similar
to how options is passed to the getActiveByPostId call on the next line.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 56da3e91-4789-4395-80e5-db178f74d2b8

📥 Commits

Reviewing files that changed from the base of the PR and between 1b0362f and 3332e19.

📒 Files selected for processing (14)
  • ghost/core/core/boot.js
  • ghost/core/core/server/api/endpoints/gift-links.ts
  • ghost/core/core/server/api/endpoints/index.js
  • ghost/core/core/server/api/endpoints/utils/serializers/output/gift-links.ts
  • ghost/core/core/server/api/endpoints/utils/serializers/output/index.js
  • ghost/core/core/server/services/gift-links/gift-link-bookshelf-repository.ts
  • ghost/core/core/server/services/gift-links/gift-link-repository.ts
  • ghost/core/core/server/services/gift-links/gift-link.ts
  • ghost/core/core/server/services/gift-links/gift-links-service.ts
  • ghost/core/core/server/services/gift-links/index.ts
  • ghost/core/core/server/web/api/endpoints/admin/routes.js
  • ghost/core/test/e2e-api/admin/gift-links.test.ts
  • ghost/core/test/integration/services/gift-links.test.ts
  • ghost/core/test/unit/server/services/gift-links/gift-links-service.test.ts
✅ Files skipped from review due to trivial changes (2)
  • ghost/core/core/server/services/gift-links/gift-link.ts
  • ghost/core/core/server/services/gift-links/gift-link-repository.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • ghost/core/core/server/api/endpoints/index.js
  • ghost/core/test/unit/server/services/gift-links/gift-links-service.test.ts
  • ghost/core/core/server/api/endpoints/utils/serializers/output/index.js
  • ghost/core/core/boot.js
  • ghost/core/test/integration/services/gift-links.test.ts
  • ghost/core/test/e2e-api/admin/gift-links.test.ts

Comment on lines +70 to +75
// Converge any link minted by a concurrent upsert, then return whatever
// is active afterwards: the sweep may have deactivated `created` in
// favour of a newer row, and the caller must never get an inactive token.
await this.repository.deactivateAllButMostRecent(postId);
return (await this.repository.getActiveByPostId(postId, options)) ?? created;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Preserve transaction scope in the upsert sweep call.

Line 73 drops options when calling deactivateAllButMostRecent. If upsert() is invoked with options.transacting, creation happens in-transaction while the sweep runs outside it, which can leave multiple active rows under concurrent upserts.

Proposed fix
-        await this.repository.deactivateAllButMostRecent(postId);
+        await this.repository.deactivateAllButMostRecent(postId, options);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Converge any link minted by a concurrent upsert, then return whatever
// is active afterwards: the sweep may have deactivated `created` in
// favour of a newer row, and the caller must never get an inactive token.
await this.repository.deactivateAllButMostRecent(postId);
return (await this.repository.getActiveByPostId(postId, options)) ?? created;
}
// Converge any link minted by a concurrent upsert, then return whatever
// is active afterwards: the sweep may have deactivated `created` in
// favour of a newer row, and the caller must never get an inactive token.
await this.repository.deactivateAllButMostRecent(postId, options);
return (await this.repository.getActiveByPostId(postId, options)) ?? created;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ghost/core/core/server/services/gift-links/gift-links-service.ts` around
lines 70 - 75, The deactivateAllButMostRecent method call on line 73 does not
pass the options parameter that is available in the upsert method scope. This
causes the sweep operation to execute outside any transaction context, creating
a race condition under concurrent calls. Pass the options parameter to the
deactivateAllButMostRecent call to maintain transaction consistency, similar to
how options is passed to the getActiveByPostId call on the next line.

ref https://linear.app/ghost/issue/BER-3727

- GiftLinksService (token generation, ensure/reset/resetAll/getActiveByToken) + boot init
- admin API: browse/ensure/reset/reset-all endpoints, output serializer, routes
- reset works on posts that later became ineligible (rotate a leaked link)
- per-post actions piggyback on post-edit permission, so Authors can manage gift
  links only for their own posts; Owner/Admin/Editor/Super Editor manage any
- slice 2 of 4 carving up spike #28625; stacked on BER-3726
@jonatansberg
jonatansberg force-pushed the ber-3727-gift-links-service-admin-api branch from 3332e19 to 90ac687 Compare June 17, 2026 14:17
jonatansberg added a commit that referenced this pull request Jun 18, 2026
ref https://linear.app/ghost/issue/BER-3727

- third draft of the gift-links service slice, for the team to compare against
  #28627 (soft status column) and #28693 (single-table active_post_id mirror)
- splits persistence into an append-only gift_links history table plus a
  gift_links_active pointer whose UNIQUE(post_id) is the hard "<=1 live link per
  post" guarantee; relaxing it to a composite key is how future "many live links
  per post" lands without touching history
- keeps Rob's Post aggregate + branded token domain and knex-only repository
  (drops the Bookshelf model), but maps rows with plain functions instead of
  z.codec; the snake<->camel mapping is flagged for a shared codec util
- revoke_all is a single set-based DELETE (no TOCTOU); recordRedemption is keyed
  by token so a since-reissued token still counts
jonatansberg added a commit that referenced this pull request Jun 18, 2026
ref https://linear.app/ghost/issue/BER-3727

- third draft of the gift-links service slice, for the team to compare against
  #28627 (soft status column) and #28693 (single-table active_post_id mirror)
- splits persistence into an append-only gift_links history table plus a
  gift_links_active pointer whose UNIQUE(post_id) is the hard "<=1 live link per
  post" guarantee; relaxing it to a composite key is how future "many live links
  per post" lands without touching history
- keeps Rob's Post aggregate + branded token domain and knex-only repository
  (drops the Bookshelf model), but maps rows with plain functions instead of
  z.codec; the snake<->camel mapping is flagged for a shared codec util
- revoke_all is a single set-based DELETE (no TOCTOU); recordRedemption is keyed
  by token so a since-reissued token still counts
@jonatansberg

Copy link
Copy Markdown
Member Author

Superseded by #28693 (the gift-links redesign chosen after the three-way design comparison). The remaining slices have been re-stacked onto feat/gift-links-redesign: the reader (#28629) now bases on the redesign, and the admin UI (#28630) bases on the re-stacked reader. Closing this in favour of #28693.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants