Repository navigation
Gift links: service & admin API - #28627
jonatansberg wants to merge 1 commit into
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (14)
🚧 Files skipped from review as they are similar to previous changes (10)
WalkthroughThis PR introduces a gift links feature for Ghost. A new Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
|
| 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
9a064db to
9ed7a1d
Compare
bca071c to
27420ed
Compare
9ed7a1d to
4ba013d
Compare
27420ed to
d85e91e
Compare
d85e91e to
05de009
Compare
05de009 to
61115dc
Compare
There was a problem hiding this comment.
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
📒 Files selected for processing (11)
ghost/core/core/boot.jsghost/core/core/server/api/endpoints/gift-links.jsghost/core/core/server/api/endpoints/index.jsghost/core/core/server/api/endpoints/utils/serializers/output/gift-links.jsghost/core/core/server/api/endpoints/utils/serializers/output/index.jsghost/core/core/server/services/gift-links/gift-links-service.jsghost/core/core/server/services/gift-links/index.jsghost/core/core/server/web/api/endpoints/admin/routes.jsghost/core/test/e2e-api/admin/gift-links.test.jsghost/core/test/integration/services/gift-links.test.jsghost/core/test/unit/server/services/gift-links/gift-links-service.test.js
rob-ghost
left a comment
There was a problem hiding this comment.
Can we convert new files to TypeScript?
rob-ghost
left a comment
There was a problem hiding this comment.
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.
| 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); | ||
| }); |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
61115dc to
1b0362f
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (1)
ghost/core/core/server/api/endpoints/gift-links.ts (1)
64-68: ⚡ Quick winAlign the eligibility docblock with the implemented reset behavior.
This comment still says eligibility is enforced for both create and reset, but
resetintentionally 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
📒 Files selected for processing (11)
ghost/core/core/boot.jsghost/core/core/server/api/endpoints/gift-links.tsghost/core/core/server/api/endpoints/index.jsghost/core/core/server/api/endpoints/utils/serializers/output/gift-links.tsghost/core/core/server/api/endpoints/utils/serializers/output/index.jsghost/core/core/server/services/gift-links/gift-links-service.tsghost/core/core/server/services/gift-links/index.tsghost/core/core/server/web/api/endpoints/admin/routes.jsghost/core/test/e2e-api/admin/gift-links.test.tsghost/core/test/integration/services/gift-links.test.tsghost/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
left a comment
There was a problem hiding this comment.
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.
1b0362f to
3332e19
Compare
|
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 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 API shape (Kevin). Nested: Concurrency. The All gift-links suites (unit/integration/e2e + reader) are green and |
There was a problem hiding this comment.
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
📒 Files selected for processing (14)
ghost/core/core/boot.jsghost/core/core/server/api/endpoints/gift-links.tsghost/core/core/server/api/endpoints/index.jsghost/core/core/server/api/endpoints/utils/serializers/output/gift-links.tsghost/core/core/server/api/endpoints/utils/serializers/output/index.jsghost/core/core/server/services/gift-links/gift-link-bookshelf-repository.tsghost/core/core/server/services/gift-links/gift-link-repository.tsghost/core/core/server/services/gift-links/gift-link.tsghost/core/core/server/services/gift-links/gift-links-service.tsghost/core/core/server/services/gift-links/index.tsghost/core/core/server/web/api/endpoints/admin/routes.jsghost/core/test/e2e-api/admin/gift-links.test.tsghost/core/test/integration/services/gift-links.test.tsghost/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
| // 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; | ||
| } |
There was a problem hiding this comment.
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.
| // 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
3332e19 to
90ac687
Compare
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
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
|
Superseded by #28693 (the gift-links redesign chosen after the three-way design comparison). The remaining slices have been re-stacked onto |

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
services/gift-links): token generation,ensure/reset/resetAll/getActive/getActiveByToken/recordRead, transaction-safe withforUpdatepost locking; wired into bootinitServices.api/endpoints/gift-links.js+ output serializer + routes):read,ensure,reset,reset_allendpoints, all gated behind thegiftLinksprivate flag.Reset-eligibility fix
The
resetendpoint now uses the lenient "post exists" check (findPostOrThrow) instead ofvalidateEligiblePost. 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.ensurestill requires eligibility. Added an e2e test covering: mint on a members-only post → flip to public →ensure422s butresetsucceeds.Tests
giftLinkslabs flag, passingEverything is behind the off-by-default
giftLinksflag.