diff --git a/apps/web/e2e/tests/platform/keys-ui.spec.ts b/apps/web/e2e/tests/platform/keys-ui.spec.ts index eaa1d01a30..38968150f1 100644 --- a/apps/web/e2e/tests/platform/keys-ui.spec.ts +++ b/apps/web/e2e/tests/platform/keys-ui.spec.ts @@ -195,7 +195,11 @@ test( await api.post('/api/v1/boards', { data: { name: `Nope ${marker}` } }), "Requires the 'board.manage' permission" ) - await expectJson(await api.get('/api/v1/help-center/articles'), 200) + // Help center reads need read:article, which this key does not hold. + await expectForbidden( + await api.get('/api/v1/help-center/articles'), + "This API key is missing the 'read:article' scope" + ) await api.dispose() await owner.api.dispose() } diff --git a/apps/web/e2e/tests/platform/keys.spec.ts b/apps/web/e2e/tests/platform/keys.spec.ts index 5863c93daf..33667ed820 100644 --- a/apps/web/e2e/tests/platform/keys.spec.ts +++ b/apps/web/e2e/tests/platform/keys.spec.ts @@ -633,12 +633,16 @@ test.describe('Scopes on the non-support resources', () => { '/api/v1/tags', '/api/v1/statuses', '/api/v1/roadmaps', - '/api/v1/help-center/articles', '/api/v1/status/summary', ]) { const res = await chat.api.get(path) expect(res.status(), `${path}: ${await res.text()}`).toBe(200) } + // Help center reads need read:article, even for what is public. + await expectForbidden( + await chat.api.get('/api/v1/help-center/articles'), + "This API key is missing the 'read:article' scope" + ) await chat.api.dispose() } ) diff --git a/apps/web/src/components/help-center/__tests__/help-center-article-feedback.test.tsx b/apps/web/src/components/help-center/__tests__/help-center-article-feedback.test.tsx index cc25cf0a70..4730fb16b1 100644 --- a/apps/web/src/components/help-center/__tests__/help-center-article-feedback.test.tsx +++ b/apps/web/src/components/help-center/__tests__/help-center-article-feedback.test.tsx @@ -58,6 +58,25 @@ describe('HelpCenterArticleFeedback', () => { expect(screen.getByRole('textbox')).toBeTruthy() }) + it('changes the vote already cast rather than casting a second one', async () => { + renderFeedback() + + fireEvent.click(screen.getByRole('button', { name: /yes/i })) + await waitFor(() => expect(recordFeedback).toHaveBeenCalledTimes(1)) + expect(recordFeedback.mock.calls[0][0]).toEqual({ + data: { articleId: 'article_1', helpful: true }, + }) + + await voteUnhelpful() + expect(recordFeedback.mock.calls[1][0]).toEqual({ + data: { + articleId: 'article_1', + helpful: false, + replacesFeedbackId: 'kb_article_feedback_1', + }, + }) + }) + it('sends the typed reason against the vote it explains', async () => { renderFeedback() await voteUnhelpful() diff --git a/apps/web/src/components/help-center/help-center-article-feedback.tsx b/apps/web/src/components/help-center/help-center-article-feedback.tsx index 146cb9d2bc..4e47d1d783 100644 --- a/apps/web/src/components/help-center/help-center-article-feedback.tsx +++ b/apps/web/src/components/help-center/help-center-article-feedback.tsx @@ -38,8 +38,14 @@ export function HelpCenterArticleFeedback({ try { // The vote lands on the click, before any typing: a visitor who never // writes a word still counts, and the reason stays optional. + // Sending back the vote already cast turns a changed mind into a change + // of that vote, rather than a second vote, for a signed-out visitor too. const result = await recordArticleFeedbackFn({ - data: { articleId: articleId as KbArticleId, helpful }, + data: { + articleId: articleId as KbArticleId, + helpful, + ...(feedbackId ? { replacesFeedbackId: feedbackId } : {}), + }, }) setFeedback(newFeedback) setFeedbackId((result.feedbackId as KbArticleFeedbackId) ?? null) diff --git a/apps/web/src/lib/server/domains/api/auth.ts b/apps/web/src/lib/server/domains/api/auth.ts index 3dd0f0ec6e..674c8b9f56 100644 --- a/apps/web/src/lib/server/domains/api/auth.ts +++ b/apps/web/src/lib/server/domains/api/auth.ts @@ -233,6 +233,18 @@ export function assertApiPermissions( } } +/** + * Whether a key's authority holds a permission: the resolved permission set + * grants it AND, for a scoped key, the key holds the scope it maps to. For a + * read that answers everyone but shows more to keys that hold the permission. + */ +export function apiKeyHolds(auth: ApiAuthContext, permission: PermissionKey): boolean { + return ( + auth.permissions.has(permission) && + hasApiScope(auth.apiKey.scopes, scopeForPermission(permission)) + ) +} + /** * Assert a key holds a scope, for a read whose rows are authorized one by one * rather than by a single permission. Legacy keys (NULL scopes) hold every diff --git a/apps/web/src/lib/server/domains/api/schemas/help-center.ts b/apps/web/src/lib/server/domains/api/schemas/help-center.ts index b2b3b8db87..1b8aecf1f8 100644 --- a/apps/web/src/lib/server/domains/api/schemas/help-center.ts +++ b/apps/web/src/lib/server/domains/api/schemas/help-center.ts @@ -131,12 +131,15 @@ const articleIdParam = { } as const const MANAGE = 'Requires the help_center.manage permission.' +const PUBLIC_READ = + 'Requires the read:article scope. A key reads what is published to everyone; drafts, private categories and segment-gated content need the help_center.manage permission.' registerPath('/help-center/categories', { get: { tags: ['Help Center'], summary: 'List help center categories', - description: 'Returns every category with its article count.', + description: + 'Requires the read:article scope. Returns every category with its article count. A key without the help_center.manage permission gets the public categories only, counted by the articles everyone can open.', responses: { 200: { description: 'List of categories', @@ -144,7 +147,7 @@ registerPath('/help-center/categories', { 'application/json': { schema: z.object({ data: z.array(CategoryWithCountSchema) }) }, }, }, - ...errorResponses(), + ...errorResponses(403), ...featureOff, }, }, @@ -173,6 +176,7 @@ registerPath('/help-center/categories/{categoryId}', { get: { tags: ['Help Center'], summary: 'Get a help center category', + description: PUBLIC_READ, parameters: [categoryIdParam], responses: { 200: { @@ -181,7 +185,7 @@ registerPath('/help-center/categories/{categoryId}', { 'application/json': { schema: createItemResponseSchema(CategorySchema, 'Category') }, }, }, - ...errorResponses(400), + ...errorResponses(400, 403), ...featureOff, }, }, @@ -222,7 +226,8 @@ registerPath('/help-center/articles', { get: { tags: ['Help Center'], summary: 'List help center articles', - description: 'Returns articles newest first, with cursor pagination.', + description: + 'Requires the read:article scope. Returns articles newest first, with cursor pagination. A key without the help_center.manage permission gets published public articles only, whatever the status filter.', parameters: [ { name: 'categoryId', @@ -269,7 +274,7 @@ registerPath('/help-center/articles', { }, }, }, - ...errorResponses(), + ...errorResponses(403), ...featureOff, }, }, @@ -298,6 +303,7 @@ registerPath('/help-center/articles/{articleId}', { get: { tags: ['Help Center'], summary: 'Get a help center article', + description: PUBLIC_READ, parameters: [articleIdParam], responses: { 200: { @@ -306,7 +312,7 @@ registerPath('/help-center/articles/{articleId}', { 'application/json': { schema: createItemResponseSchema(ArticleSchema, 'Article') }, }, }, - ...errorResponses(400), + ...errorResponses(400, 403), ...featureOff, }, }, @@ -347,7 +353,8 @@ registerPath('/help-center/articles/{articleId}/feedback', { post: { tags: ['Help Center'], summary: 'Record article feedback', - description: 'Records whether the article was helpful, on behalf of the API key owner.', + description: + 'Records whether the article was helpful, on behalf of the API key owner. Requires the read:article scope; a draft, or an article in a private or gated category, needs the help_center.manage permission.', parameters: [articleIdParam], requestBody: { required: true, @@ -362,7 +369,7 @@ registerPath('/help-center/articles/{articleId}/feedback', { }, }, }, - ...errorResponses(400), + ...errorResponses(400, 403), ...featureOff, }, }, diff --git a/apps/web/src/lib/server/domains/help-center/__tests__/help-center-category.service.test.ts b/apps/web/src/lib/server/domains/help-center/__tests__/help-center-category.service.test.ts index 03d16ae91d..01728635b2 100644 --- a/apps/web/src/lib/server/domains/help-center/__tests__/help-center-category.service.test.ts +++ b/apps/web/src/lib/server/domains/help-center/__tests__/help-center-category.service.test.ts @@ -125,6 +125,15 @@ vi.mock('@/lib/server/db', () => ({ inArray: vi.fn(), })) +/** The public list's per-category count of articles the viewer can open. */ +function visibleArticleCounts(rows: Array<{ categoryId: string; visibleCount: number }>) { + mockSelectFrom.mockReturnValue({ + innerJoin: vi.fn().mockReturnValue({ + where: vi.fn().mockReturnValue({ groupBy: vi.fn().mockResolvedValue(rows) }), + }), + }) +} + let listCategories: typeof import('../help-center.category.service').listCategories let listPublicCategories: typeof import('../help-center.category.service').listPublicCategories let getCategoryById: typeof import('../help-center.category.service').getCategoryById @@ -287,14 +296,10 @@ describe('listPublicCategories', () => { }, ]) - mockSelectFrom.mockReturnValue({ - where: vi.fn().mockReturnValue({ - groupBy: vi.fn().mockResolvedValue([ - { categoryId: 'kb_category_1', totalCount: 2, publishedCount: 2 }, - { categoryId: 'kb_category_2', totalCount: 1, publishedCount: 1 }, - ]), - }), - }) + visibleArticleCounts([ + { categoryId: 'kb_category_1', visibleCount: 2 }, + { categoryId: 'kb_category_2', visibleCount: 1 }, + ]) const result = await listPublicCategories() expect(result).toHaveLength(1) @@ -341,15 +346,7 @@ describe('listPublicCategories', () => { }, ]) - mockSelectFrom.mockReturnValue({ - where: vi.fn().mockReturnValue({ - groupBy: vi - .fn() - .mockResolvedValue([ - { categoryId: 'kb_category_child', totalCount: 14, publishedCount: 14 }, - ]), - }), - }) + visibleArticleCounts([{ categoryId: 'kb_category_child', visibleCount: 14 }]) const result = await listPublicCategories() const slugs = result.map((c) => c.slug).sort() @@ -601,13 +598,7 @@ describe('listPublicCategories returns parentId and icon', () => { }, ]) - mockSelectFrom.mockReturnValue({ - where: vi.fn().mockReturnValue({ - groupBy: vi - .fn() - .mockResolvedValue([{ categoryId: 'kb_category_1', totalCount: 2, publishedCount: 2 }]), - }), - }) + visibleArticleCounts([{ categoryId: 'kb_category_1', visibleCount: 2 }]) const result = await listPublicCategories() expect(result).toHaveLength(1) diff --git a/apps/web/src/lib/server/domains/help-center/__tests__/help-center-public-access.db.test.ts b/apps/web/src/lib/server/domains/help-center/__tests__/help-center-public-access.db.test.ts new file mode 100644 index 0000000000..0a3d7da7f9 --- /dev/null +++ b/apps/web/src/lib/server/domains/help-center/__tests__/help-center-public-access.db.test.ts @@ -0,0 +1,177 @@ +/** + * Public help center reads against a real database: what the landing cards + * count, and how a signed-out visitor's vote is kept. + */ +import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createId } from '@quackback/ids' +import type { KbArticleId, KbCategoryId, PrincipalId, SegmentId } from '@quackback/ids' +import { + eq, + helpCenterArticleFeedback, + helpCenterArticles, + helpCenterCategories, + principal, +} from '@/lib/server/db' +import { createDbTestFixture, testDb } from '@/lib/server/__tests__/db-test-fixture' +import { ANONYMOUS_ACTOR, type Actor } from '@/lib/server/policy/types' + +vi.mock('@/lib/server/db', async (original) => ({ + ...(await original()), + db: (await import('@/lib/server/__tests__/db-test-fixture')).testDb, +})) + +import { listPublicCategories } from '../help-center.category.service' +import { recordArticleFeedback } from '../help-center.article-feedback.service' + +const fixture = await createDbTestFixture({ + probe: async (db) => { + await db + .select({ id: helpCenterArticleFeedback.id, segmentIds: helpCenterArticles.segmentIds }) + .from(helpCenterArticleFeedback) + .innerJoin(helpCenterArticles, eq(helpCenterArticles.id, helpCenterArticleFeedback.articleId)) + .limit(0) + }, +}) + +const SEGMENT = createId('segment') as SegmentId +const AUTHOR = createId('principal') as PrincipalId +const member: Actor = { + principalId: createId('principal') as PrincipalId, + role: 'user', + principalType: 'user', + segmentIds: new Set([SEGMENT]), +} + +async function category( + name: string, + opts: { parentId?: KbCategoryId; isPublic?: boolean; segmentIds?: string[] } = {} +): Promise { + const id = createId('kb_category') as KbCategoryId + await testDb.insert(helpCenterCategories).values({ + id, + slug: `${name}-${id}`, + name, + isPublic: opts.isPublic ?? true, + parentId: opts.parentId ?? null, + segmentIds: opts.segmentIds ?? [], + }) + return id +} + +async function article( + categoryId: KbCategoryId, + opts: { published?: boolean; segmentIds?: string[] } = {} +): Promise { + const id = createId('kb_article') as KbArticleId + await testDb.insert(helpCenterArticles).values({ + id, + categoryId, + slug: `article-${id}`, + title: `Article ${id}`, + content: 'Body', + principalId: AUTHOR, + publishedAt: opts.published === false ? null : new Date(Date.now() - 60_000), + segmentIds: opts.segmentIds ?? [], + }) + return id +} + +describe.skipIf(!fixture.available)('public help center against the database', () => { + beforeEach(async () => { + await fixture.begin() + await testDb.insert(principal).values({ id: AUTHOR, createdAt: new Date() }) + }) + afterEach(fixture.rollback) + afterAll(fixture.close) + + describe('the landing card count', () => { + it('counts only the articles the viewer can open', async () => { + const parent = await category('Counted') + await article(parent) + await article(parent, { published: false }) + await article(parent, { segmentIds: [SEGMENT] }) + const privateChild = await category('Hidden child', { parentId: parent, isPublic: false }) + for (let i = 0; i < 3; i++) await article(privateChild) + // A public grandchild under the private child is not reachable from the card. + const orphan = await category('Orphan', { parentId: privateChild }) + await article(orphan) + const gatedChild = await category('Gated child', { parentId: parent, segmentIds: [SEGMENT] }) + await article(gatedChild) + await article(gatedChild) + const openChild = await category('Open child', { parentId: parent }) + await article(openChild) + + const forAnonymous = (await listPublicCategories(ANONYMOUS_ACTOR)).find( + (c) => c.id === parent + ) + expect(forAnonymous?.articleCount).toBe(2) + expect(forAnonymous?.recursivePublishedArticleCount).toBe(2) + + const forMember = (await listPublicCategories(member)).find((c) => c.id === parent) + expect(forMember?.articleCount).toBe(5) + }) + + it('drops a category whose only articles the viewer cannot open', async () => { + const parent = await category('Only hidden') + await article(parent, { segmentIds: [SEGMENT] }) + const privateChild = await category('Private child', { parentId: parent, isPublic: false }) + await article(privateChild) + + const ids = (await listPublicCategories(ANONYMOUS_ACTOR)).map((c) => c.id) + expect(ids).not.toContain(parent) + expect(ids).not.toContain(privateChild) + expect((await listPublicCategories(member)).map((c) => c.id)).toContain(parent) + }) + }) + + describe('a signed-out vote', () => { + async function counts(id: KbArticleId) { + const [row] = await testDb + .select({ + helpful: helpCenterArticles.helpfulCount, + notHelpful: helpCenterArticles.notHelpfulCount, + }) + .from(helpCenterArticles) + .where(eq(helpCenterArticles.id, id)) + const votes = await testDb + .select({ helpful: helpCenterArticleFeedback.helpful }) + .from(helpCenterArticleFeedback) + .where(eq(helpCenterArticleFeedback.articleId, id)) + return { ...row, rows: votes.map((v) => v.helpful) } + } + + it('replaces the earlier vote when the visitor changes their mind', async () => { + const id = await article(await category('Votes')) + const first = await recordArticleFeedback(id, true, null) + const second = await recordArticleFeedback(id, false, null, { replaces: first }) + + expect(second).toBe(first) + expect(await counts(id)).toEqual({ helpful: 0, notHelpful: 1, rows: [false] }) + }) + + it('leaves the counters alone when the same vote is sent again', async () => { + const id = await article(await category('Votes')) + const first = await recordArticleFeedback(id, true, null) + await recordArticleFeedback(id, true, null, { replaces: first }) + + expect(await counts(id)).toEqual({ helpful: 1, notHelpful: 0, rows: [true] }) + }) + + it('never rewrites a signed-in visitor vote or a vote on another article', async () => { + const voter = createId('principal') as PrincipalId + await testDb.insert(principal).values({ id: voter, createdAt: new Date() }) + const id = await article(await category('Votes')) + const other = await article(await category('Other')) + const signedIn = await recordArticleFeedback(id, true, voter) + const elsewhere = await recordArticleFeedback(other, true, null) + + const a = await recordArticleFeedback(id, false, null, { replaces: signedIn }) + const b = await recordArticleFeedback(id, false, null, { replaces: elsewhere }) + + expect(a).not.toBe(signedIn) + expect(b).not.toBe(elsewhere) + expect((await counts(id)).rows.sort()).toEqual([false, false, true]) + expect(await counts(other)).toEqual({ helpful: 1, notHelpful: 0, rows: [true] }) + }) + }) +}) diff --git a/apps/web/src/lib/server/domains/help-center/help-center-api-access.ts b/apps/web/src/lib/server/domains/help-center/help-center-api-access.ts new file mode 100644 index 0000000000..6466063234 --- /dev/null +++ b/apps/web/src/lib/server/domains/help-center/help-center-api-access.ts @@ -0,0 +1,76 @@ +/** + * What an API key may see of the help center. + * + * Every help center read and vote needs the `read:article` scope. With it, a + * key reads what is published to everyone. Drafts, private categories and + * segment-gated content are team material and need `help_center.manage`, + * including the scope that permission maps to. + */ +import { apiKeyHolds, assertApiScope, type ApiAuthContext } from '@/lib/server/domains/api/auth' +import { + getArticleById, + getCategoryById, + getPublicArticleById, + getPublicCategoryById, +} from '@/lib/server/domains/help-center/help-center.service' +import { ForbiddenError, NotFoundError } from '@/lib/shared/errors' +import { PERMISSIONS } from '@/lib/shared/permissions' +import type { KbArticleId, KbCategoryId } from '@quackback/ids' + +export interface HelpCenterApiAccess { + auth: ApiAuthContext + /** True for a key that holds help_center.manage: it sees team material too. */ + manages: boolean +} + +/** + * What an authenticated key may do with the help center. Each route calls + * `withApiKeyAuth` itself, so the authorization matrix still lists it. + */ +export function helpCenterApiAccess(auth: ApiAuthContext): HelpCenterApiAccess { + assertApiScope(auth, 'read:article') + return { auth, manages: apiKeyHolds(auth, PERMISSIONS.HELP_CENTER_MANAGE) } +} + +const closed = (what: string) => + new ForbiddenError( + 'FORBIDDEN', + `Requires the '${PERMISSIONS.HELP_CENTER_MANAGE}' permission to use ${what}` + ) + +/** + * Refuse an article the key may not see: 404 when there is no such article, + * 403 when it exists but is not published to everyone. A key that manages the + * help center sees every article, so its caller's own lookup answers 404. + */ +export async function assertArticleOpenToKey( + access: HelpCenterApiAccess, + articleId: KbArticleId +): Promise { + if (access.manages) return + try { + await getPublicArticleById(articleId) + } catch (error) { + if (!(error instanceof NotFoundError)) throw error + await getArticleById(articleId) + throw closed('an article that is not published to everyone') + } +} + +/** + * Refuse a category the key may not see: 404 when there is no such category, + * 403 when it exists but is private or gated. + */ +export async function assertCategoryOpenToKey( + access: HelpCenterApiAccess, + categoryId: KbCategoryId +): Promise { + if (access.manages) return + try { + await getPublicCategoryById(categoryId) + } catch (error) { + if (!(error instanceof NotFoundError)) throw error + await getCategoryById(categoryId) + throw closed('a category that is not public') + } +} diff --git a/apps/web/src/lib/server/domains/help-center/help-center.article-feedback.service.ts b/apps/web/src/lib/server/domains/help-center/help-center.article-feedback.service.ts index f482687de3..0667f6dcef 100644 --- a/apps/web/src/lib/server/domains/help-center/help-center.article-feedback.service.ts +++ b/apps/web/src/lib/server/domains/help-center/help-center.article-feedback.service.ts @@ -17,17 +17,29 @@ import { logger } from '@/lib/server/logger' const log = logger.child({ component: 'help-center-article-feedback' }) +export interface RecordArticleFeedbackOptions { + /** + * The vote this visitor cast earlier on the page. A signed-out visitor has + * no principal to find that vote by, so the id they were handed back is how + * a changed mind replaces the vote rather than adding a second one. Ignored + * for a signed-in visitor, whose vote is found by principal. + */ + replaces?: KbArticleFeedbackId | null +} + /** * Records a helpful/unhelpful vote and returns the id of the row that holds it. * * The caller needs that id to attach a free-text reason afterwards: an * anonymous visitor has no principal to look the row back up by, so the id is - * the only handle on their own vote. + * the only handle on their own vote. Passed back as `replaces`, it turns a + * changed mind into a flip of that vote. */ export async function recordArticleFeedback( articleId: KbArticleId, helpful: boolean, - principalId?: PrincipalId | null + principalId?: PrincipalId | null, + options: RecordArticleFeedbackOptions = {} ): Promise { return db.transaction(async (tx) => { const article = await tx.query.helpCenterArticles.findFirst({ @@ -36,32 +48,52 @@ export async function recordArticleFeedback( }) if (!article) throw new NotFoundError('ARTICLE_NOT_FOUND', `Article ${articleId} not found`) - if (principalId) { + // A signed-in visitor's vote is theirs by principal. A signed-out one is + // found only by the id they hold, and only when it is a signed-out vote on + // this same article, so a vote id never reaches anyone else's vote. + const owned = principalId + ? eq(helpCenterArticleFeedback.principalId, principalId) + : options.replaces + ? and( + eq(helpCenterArticleFeedback.id, options.replaces), + isNull(helpCenterArticleFeedback.principalId) + ) + : null + + if (owned) { const existing = await tx.query.helpCenterArticleFeedback.findFirst({ - where: and( - eq(helpCenterArticleFeedback.articleId, articleId), - eq(helpCenterArticleFeedback.principalId, principalId) - ), + where: and(eq(helpCenterArticleFeedback.articleId, articleId), owned), + columns: { id: true, helpful: true }, }) if (existing) { if (existing.helpful === helpful) return existing.id // A reason explains an unhelpful vote, so it does not survive the flip. - await tx + // The counters move only when this update flipped the row, so two + // racing flips cannot move them twice. + const flipped = await tx .update(helpCenterArticleFeedback) .set({ helpful, reason: null }) - .where(eq(helpCenterArticleFeedback.id, existing.id)) - await tx - .update(helpCenterArticles) - .set({ - helpfulCount: helpful - ? sql`${helpCenterArticles.helpfulCount} + 1` - : sql`${helpCenterArticles.helpfulCount} - 1`, - notHelpfulCount: helpful - ? sql`${helpCenterArticles.notHelpfulCount} - 1` - : sql`${helpCenterArticles.notHelpfulCount} + 1`, - }) - .where(eq(helpCenterArticles.id, articleId)) + .where( + and( + eq(helpCenterArticleFeedback.id, existing.id), + eq(helpCenterArticleFeedback.helpful, !helpful) + ) + ) + .returning({ id: helpCenterArticleFeedback.id }) + if (flipped.length > 0) { + await tx + .update(helpCenterArticles) + .set({ + helpfulCount: helpful + ? sql`${helpCenterArticles.helpfulCount} + 1` + : sql`${helpCenterArticles.helpfulCount} - 1`, + notHelpfulCount: helpful + ? sql`${helpCenterArticles.notHelpfulCount} - 1` + : sql`${helpCenterArticles.notHelpfulCount} + 1`, + }) + .where(eq(helpCenterArticles.id, articleId)) + } return existing.id } } diff --git a/apps/web/src/lib/server/domains/help-center/help-center.category.service.ts b/apps/web/src/lib/server/domains/help-center/help-center.category.service.ts index d102bad5a5..df430829e8 100644 --- a/apps/web/src/lib/server/domains/help-center/help-center.category.service.ts +++ b/apps/web/src/lib/server/domains/help-center/help-center.category.service.ts @@ -33,6 +33,8 @@ import { } from './category-tree' import { logger } from '@/lib/server/logger' +export { listPublicCategories } from './help-center.public-category.query' + const log = logger.child({ component: 'help-center-categories' }) // ============================================================================ @@ -172,22 +174,6 @@ export async function listCategories( }) } -export async function listPublicCategories( - viewer: Actor = ANONYMOUS_ACTOR -): Promise { - const all = await listCategories() - return all - .filter( - (cat) => - cat.isPublic && - // Segment gate ([] = everyone) — same per-category semantics as the - // article-side SQL predicate (helpCenterVisibilityConditions). - segmentGateAllows(viewer, cat.segmentIds) && - cat.recursivePublishedArticleCount > 0 - ) - .map((cat) => ({ ...cat, articleCount: cat.recursivePublishedArticleCount })) -} - export async function getCategoryById(id: KbCategoryId): Promise { const category = await db.query.helpCenterCategories.findFirst({ where: and(eq(helpCenterCategories.id, id), isNull(helpCenterCategories.deletedAt)), diff --git a/apps/web/src/lib/server/domains/help-center/help-center.public-category.query.ts b/apps/web/src/lib/server/domains/help-center/help-center.public-category.query.ts new file mode 100644 index 0000000000..de600b5c53 --- /dev/null +++ b/apps/web/src/lib/server/domains/help-center/help-center.public-category.query.ts @@ -0,0 +1,65 @@ +import { + db, + helpCenterCategories, + helpCenterArticles, + eq, + and, + isNull, + asc, + sql, +} from '@/lib/server/db' +import { ANONYMOUS_ACTOR, type Actor } from '@/lib/server/policy/types' +import { segmentGateAllows } from '@/lib/server/policy/segment-gate' +import { helpCenterVisibilityConditions } from './help-center-search.service' +import { computeRecursiveCounts } from './category-tree' +import type { HelpCenterCategoryWithCount } from './help-center.types' + +/** + * The categories a help center visitor can open, each counted by the articles + * that visitor can open: published, not gated away from them, in a category + * they can open. A subcategory the visitor cannot open adds nothing to its + * parent's count, nor does anything beneath it, since the visitor cannot + * reach it from the parent's page either. + */ +export async function listPublicCategories( + viewer: Actor = ANONYMOUS_ACTOR +): Promise { + const [categories, counts] = await Promise.all([ + db.query.helpCenterCategories.findMany({ + where: isNull(helpCenterCategories.deletedAt), + orderBy: [asc(helpCenterCategories.position), asc(helpCenterCategories.name)], + }), + db + .select({ + categoryId: helpCenterArticles.categoryId, + visibleCount: sql`count(*)::int`.as('visible_count'), + }) + .from(helpCenterArticles) + .innerJoin(helpCenterCategories, eq(helpCenterCategories.id, helpCenterArticles.categoryId)) + .where(and(...helpCenterVisibilityConditions('public', viewer))) + .groupBy(helpCenterArticles.categoryId), + ]) + + // Same per-category semantics as the article-side predicate + // (helpCenterVisibilityConditions): public, and the segment gate admits the + // viewer ([] = everyone). + const open = categories.filter((cat) => cat.isPublic && segmentGateAllows(viewer, cat.segmentIds)) + const direct = new Map(counts.map((c) => [c.categoryId as string, c.visibleCount])) + const recursive = computeRecursiveCounts( + open.map((c) => ({ id: c.id, parentId: c.parentId ?? null })), + (id) => direct.get(id) ?? 0 + ) + + return open + .map((cat) => { + const total = recursive.get(cat.id) ?? 0 + return { + ...cat, + articleCount: total, + publishedArticleCount: direct.get(cat.id) ?? 0, + recursiveArticleCount: total, + recursivePublishedArticleCount: total, + } + }) + .filter((cat) => cat.articleCount > 0) +} diff --git a/apps/web/src/lib/server/functions/help-center.ts b/apps/web/src/lib/server/functions/help-center.ts index f6adf9cc2f..d9e29ca9e1 100644 --- a/apps/web/src/lib/server/functions/help-center.ts +++ b/apps/web/src/lib/server/functions/help-center.ts @@ -536,10 +536,11 @@ export const recordArticleFeedbackFn = createServerFn({ method: 'POST' }) const feedbackId = await recordArticleFeedback( data.articleId as KbArticleId, data.helpful, - (auth?.principal?.id as PrincipalId) ?? null + (auth?.principal?.id as PrincipalId) ?? null, + { replaces: (data.replacesFeedbackId as KbArticleFeedbackId | undefined) ?? null } ) // The id is the visitor's handle on their own vote, and the only one an - // anonymous visitor has for attaching a reason to it afterwards. + // anonymous visitor has for attaching a reason to it, or for changing it. return { success: true, feedbackId } }) diff --git a/apps/web/src/lib/server/policy/authz-matrix/MATRIX.md b/apps/web/src/lib/server/policy/authz-matrix/MATRIX.md index 99c164273d..f55c61a139 100644 --- a/apps/web/src/lib/server/policy/authz-matrix/MATRIX.md +++ b/apps/web/src/lib/server/policy/authz-matrix/MATRIX.md @@ -930,16 +930,16 @@ Profiles: **Owner** = admin class + an admin-owned full API key (scoped keys hol | `routes/api/v1/conversations/$conversationId.ts`::GET | conversation.view | | `routes/api/v1/conversations/index.ts`::GET | conversation.view | | `routes/api/v1/files/index.ts`::POST | conversation.reply | -| `routes/api/v1/help-center/articles/$articleId.feedback.ts`::POST | PUBLIC (any valid key) | -| `routes/api/v1/help-center/articles/$articleId.ts`::GET | PUBLIC (any valid key) | +| `routes/api/v1/help-center/articles/$articleId.feedback.ts`::POST | DYNAMIC (help_center.manage) | +| `routes/api/v1/help-center/articles/$articleId.ts`::GET | DYNAMIC (help_center.manage) | | `routes/api/v1/help-center/articles/$articleId.ts`::PATCH | help_center.manage | | `routes/api/v1/help-center/articles/$articleId.ts`::DELETE | help_center.manage | -| `routes/api/v1/help-center/articles/index.ts`::GET | PUBLIC (any valid key) | +| `routes/api/v1/help-center/articles/index.ts`::GET | DYNAMIC (help_center.manage) | | `routes/api/v1/help-center/articles/index.ts`::POST | help_center.manage | -| `routes/api/v1/help-center/categories/$categoryId.ts`::GET | PUBLIC (any valid key) | +| `routes/api/v1/help-center/categories/$categoryId.ts`::GET | DYNAMIC (help_center.manage) | | `routes/api/v1/help-center/categories/$categoryId.ts`::PATCH | help_center.manage | | `routes/api/v1/help-center/categories/$categoryId.ts`::DELETE | help_center.manage | -| `routes/api/v1/help-center/categories/index.ts`::GET | PUBLIC (any valid key) | +| `routes/api/v1/help-center/categories/index.ts`::GET | DYNAMIC (help_center.manage) | | `routes/api/v1/help-center/categories/index.ts`::POST | help_center.manage | | `routes/api/v1/moderation/comments.$commentId.approve.ts`::POST | post.approve | | `routes/api/v1/moderation/comments.$commentId.reject.ts`::POST | post.approve | diff --git a/apps/web/src/lib/server/policy/authz-matrix/classifications.ts b/apps/web/src/lib/server/policy/authz-matrix/classifications.ts index 8cd0a70a8f..e7cebba6c0 100644 --- a/apps/web/src/lib/server/policy/authz-matrix/classifications.ts +++ b/apps/web/src/lib/server/policy/authz-matrix/classifications.ts @@ -718,12 +718,29 @@ export const BARE_GATE_CLASSIFICATIONS: Record = { PUBLIC_DATA('public status service'), 'routes/api/v1/status/incidents/index.ts::GET': PUBLIC_DATA('public status incident list'), 'routes/api/v1/status/incidents/$incidentId.ts::GET': PUBLIC_DATA('public status incident'), - 'routes/api/v1/help-center/articles/$articleId.feedback.ts::POST': - PUBLIC_DATA('end-user article rating'), - 'routes/api/v1/help-center/articles/$articleId.ts::GET': PUBLIC_DATA('public help article'), - 'routes/api/v1/help-center/articles/index.ts::GET': PUBLIC_DATA('public help article list'), - 'routes/api/v1/help-center/categories/$categoryId.ts::GET': PUBLIC_DATA('public help category'), - 'routes/api/v1/help-center/categories/index.ts::GET': PUBLIC_DATA('public help category list'), + // Help center reads and the article vote by key (helpCenterApiAccess): any + // key with read:article gets what is published to everyone; drafts, private + // and gated content need help_center.manage. + 'routes/api/v1/help-center/articles/$articleId.feedback.ts::POST': DYNAMIC_PERMISSION( + [PERMISSIONS.HELP_CENTER_MANAGE], + 'article rating: read:article for a public article, help_center.manage for any other' + ), + 'routes/api/v1/help-center/articles/$articleId.ts::GET': DYNAMIC_PERMISSION( + [PERMISSIONS.HELP_CENTER_MANAGE], + 'help article: read:article for a public article, help_center.manage for any other' + ), + 'routes/api/v1/help-center/articles/index.ts::GET': DYNAMIC_PERMISSION( + [PERMISSIONS.HELP_CENTER_MANAGE], + 'help article list: read:article lists public articles, help_center.manage lists all' + ), + 'routes/api/v1/help-center/categories/$categoryId.ts::GET': DYNAMIC_PERMISSION( + [PERMISSIONS.HELP_CENTER_MANAGE], + 'help category: read:article for a public category, help_center.manage for any other' + ), + 'routes/api/v1/help-center/categories/index.ts::GET': DYNAMIC_PERMISSION( + [PERMISSIONS.HELP_CENTER_MANAGE], + 'help category list: read:article lists public categories, help_center.manage lists all' + ), 'routes/api/v1/roadmaps/$roadmapId.columns.ts::GET': PUBLIC_DATA('public roadmap columns'), 'routes/api/v1/roadmaps/$roadmapId.posts.ts::GET': PUBLIC_DATA('public roadmap posts'), 'routes/api/v1/roadmaps/$roadmapId.ts::GET': PUBLIC_DATA('public roadmap'), diff --git a/apps/web/src/lib/server/policy/dep-graph/GRAPH.md b/apps/web/src/lib/server/policy/dep-graph/GRAPH.md index 36e7b002d6..ec00a8d546 100644 --- a/apps/web/src/lib/server/policy/dep-graph/GRAPH.md +++ b/apps/web/src/lib/server/policy/dep-graph/GRAPH.md @@ -61,7 +61,7 @@ Edges (30): ## 3. Server domains (lib/server/domains) Nodes (56): activity, admin-overview, ai, analytics, api, api-keys, assistant, attribute-definitions, billing, boards, changelog, channel-accounts, channels, comments, companies, company-attributes, conversation, conversation-attributes, conversation-views, domain-proof, embeddings, export, files, help-center, import, inbox, macros, merge-suggestions, moderation, notifications, office-hours, onboarding, plan-limits, platform-credentials, post-tags, post-views, posts, principals, push-devices, roadmaps, roles, segments, sentiment, settings, settings-registry, sla, status, statuses, subscriptions, summary, teams, tickets, user-attributes, users, webhooks, workflows -Edges (179): +Edges (180): - activity -> principals - admin-overview -> changelog @@ -151,6 +151,7 @@ Edges (179): - export -> users - files -> principals - help-center -> ai +- help-center -> api - help-center -> plan-limits - help-center -> principals - help-center -> settings diff --git a/apps/web/src/lib/shared/schemas/__tests__/article-feedback-schema.test.ts b/apps/web/src/lib/shared/schemas/__tests__/article-feedback-schema.test.ts new file mode 100644 index 0000000000..ee360630d2 --- /dev/null +++ b/apps/web/src/lib/shared/schemas/__tests__/article-feedback-schema.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from 'vitest' +import { createId } from '@quackback/ids' +import { articleFeedbackSchema } from '../help-center' + +describe('articleFeedbackSchema', () => { + const vote = { articleId: 'kb_article_1', helpful: false } + + it('accepts a vote with no earlier vote to replace', () => { + expect(articleFeedbackSchema.safeParse(vote).success).toBe(true) + }) + + it('accepts the id of the earlier vote it replaces', () => { + const replacesFeedbackId = createId('kb_article_feedback') + expect(articleFeedbackSchema.parse({ ...vote, replacesFeedbackId })).toEqual({ + ...vote, + replacesFeedbackId, + }) + }) + + it('refuses a malformed id or an id of another kind', () => { + for (const replacesFeedbackId of ['not-an-id', '', createId('kb_article')]) { + expect(articleFeedbackSchema.safeParse({ ...vote, replacesFeedbackId }).success).toBe(false) + } + }) +}) diff --git a/apps/web/src/lib/shared/schemas/help-center.ts b/apps/web/src/lib/shared/schemas/help-center.ts index 4dd611dbb6..fef41e45c7 100644 --- a/apps/web/src/lib/shared/schemas/help-center.ts +++ b/apps/web/src/lib/shared/schemas/help-center.ts @@ -5,6 +5,7 @@ */ import { z } from 'zod' +import { isValidTypeId } from '@quackback/ids' import { PageLimitSchema } from './taxonomy' import { tiptapContentSchema } from './posts' import { SUPPORTED_LOCALES } from '../i18n' @@ -117,6 +118,14 @@ export const publishArticleSchema = z.object({ export const articleFeedbackSchema = z.object({ articleId: z.string().min(1), helpful: z.boolean(), + /** + * The vote this visitor cast earlier on the page, so a changed mind replaces + * it. A signed-out visitor has no other handle on their own vote. + */ + replacesFeedbackId: z + .string() + .refine((v) => isValidTypeId(v, 'kb_article_feedback'), 'Invalid feedback ID') + .optional(), }) /** Longest reason accepted from a visitor, in characters. */ diff --git a/apps/web/src/routes/api/v1/help-center/__tests__/articles.test.ts b/apps/web/src/routes/api/v1/help-center/__tests__/articles.test.ts index a43528fd43..455f0a70b1 100644 --- a/apps/web/src/routes/api/v1/help-center/__tests__/articles.test.ts +++ b/apps/web/src/routes/api/v1/help-center/__tests__/articles.test.ts @@ -7,7 +7,8 @@ import type { KbArticleFeedbackId, KbArticleId, KbCategoryId, PrincipalId } from // --- Mocks --- -vi.mock('@/lib/server/domains/api/auth', () => ({ +vi.mock('@/lib/server/domains/api/auth', async (importOriginal) => ({ + ...(await importOriginal()), withApiKeyAuth: vi.fn(), })) vi.mock('@/lib/server/domains/settings/settings.service', () => ({ diff --git a/apps/web/src/routes/api/v1/help-center/__tests__/categories.test.ts b/apps/web/src/routes/api/v1/help-center/__tests__/categories.test.ts index 2f4fb90b19..e911196b90 100644 --- a/apps/web/src/routes/api/v1/help-center/__tests__/categories.test.ts +++ b/apps/web/src/routes/api/v1/help-center/__tests__/categories.test.ts @@ -1,7 +1,8 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' // Mocks must be before imports -vi.mock('@/lib/server/domains/api/auth', () => ({ +vi.mock('@/lib/server/domains/api/auth', async (importOriginal) => ({ + ...(await importOriginal()), withApiKeyAuth: vi.fn(), })) vi.mock('@/lib/server/domains/settings/settings.service', () => ({ diff --git a/apps/web/src/routes/api/v1/help-center/__tests__/read-access.test.ts b/apps/web/src/routes/api/v1/help-center/__tests__/read-access.test.ts new file mode 100644 index 0000000000..023810c966 --- /dev/null +++ b/apps/web/src/routes/api/v1/help-center/__tests__/read-access.test.ts @@ -0,0 +1,362 @@ +/** + * Who may read what over the help center REST reads. + * + * Any valid key may read the published, public help center. Drafts, private + * categories and segment-gated content are team material: they need a key that + * holds `help_center.manage`, including the scope that permission maps to. + */ +import { describe, it, expect, vi, beforeEach } from 'vitest' + +vi.mock('@/lib/server/domains/api/auth', async (importOriginal) => ({ + ...(await importOriginal()), + withApiKeyAuth: vi.fn(), +})) +vi.mock('@/lib/server/domains/settings/settings.service', () => ({ + isFeatureEnabled: vi.fn(), +})) +vi.mock('@/lib/server/domains/help-center/help-center.service', () => ({ + listArticles: vi.fn(), + listPublicArticles: vi.fn(), + getArticleById: vi.fn(), + getPublicArticleById: vi.fn(), + listCategories: vi.fn(), + listPublicCategories: vi.fn(), + getCategoryById: vi.fn(), + getPublicCategoryById: vi.fn(), + recordArticleFeedback: vi.fn(), +})) +vi.mock('@/lib/server/domains/api/validation', () => ({ + parseTypeId: vi.fn((v: string) => v), + parseOptionalTypeId: vi.fn((v: string | null) => v ?? undefined), +})) +vi.mock('@/lib/server/domains/api/responses', async (importOriginal) => ({ + ...(await importOriginal()), + parsePaginationParams: vi.fn(() => ({ cursor: undefined, limit: 20 })), +})) +vi.mock('@tanstack/react-router', () => ({ + createFileRoute: vi.fn(() => (opts: unknown) => ({ options: opts })), +})) + +import { withApiKeyAuth, type ApiAuthContext } from '@/lib/server/domains/api/auth' +import { isFeatureEnabled } from '@/lib/server/domains/settings/settings.service' +import { + listArticles, + listPublicArticles, + getArticleById, + getPublicArticleById, + listCategories, + listPublicCategories, + getCategoryById, + getPublicCategoryById, + recordArticleFeedback, +} from '@/lib/server/domains/help-center/help-center.service' +import { NotFoundError } from '@/lib/shared/errors' +import { SYSTEM_ROLE_PERMISSIONS } from '@/lib/shared/permissions' +import type { ApiKeyId } from '@/lib/server/domains/api-keys' +import type { + HelpCenterArticleWithCategory, + HelpCenterCategory, + HelpCenterCategoryWithCount, +} from '@/lib/server/domains/help-center/help-center.types' +import type { KbArticleId, KbCategoryId, PrincipalId } from '@quackback/ids' + +import { Route as ArticlesListRoute } from '../articles/index' +import { Route as ArticleDetailRoute } from '../articles/$articleId' +import { Route as CategoriesListRoute } from '../categories/index' +import { Route as CategoryDetailRoute } from '../categories/$categoryId' +import { Route as ArticleFeedbackRoute } from '../articles/$articleId.feedback' + +type Handler = (ctx: { request: Request; params?: Record }) => Promise +type RouteShape = { options: { server: { handlers: Record } } } +const handlers = (route: unknown) => (route as RouteShape).options.server.handlers + +function keyFor( + role: 'owner' | 'contributor', + scopes: ApiAuthContext['apiKey']['scopes'] = null +): ApiAuthContext { + return { + apiKey: { + id: 'api_key_test' as ApiKeyId, + name: 'test', + kind: 'personal' as const, + keyPrefix: 'qb_', + createdById: null, + principalId: 'principal_1' as PrincipalId, + lastUsedAt: null, + expiresAt: null, + createdAt: new Date('2026-01-01'), + revokedAt: null, + scopes, + }, + principalId: 'principal_1' as PrincipalId, + role: role === 'owner' ? 'admin' : 'member', + permissions: new Set(SYSTEM_ROLE_PERMISSIONS[role]), + principal: null, + importMode: false, + } +} + +const contributor = keyFor('contributor') +const owner = keyFor('owner') +/** An owner's key narrowed to reading: it does not carry help_center.manage. */ +const readOnlyOwner = keyFor('owner', ['read:article']) + +const draft: HelpCenterArticleWithCategory = { + id: 'kb_article_1' as KbArticleId, + categoryId: 'kb_category_1' as KbCategoryId, + slug: 'secret', + title: 'Secret plan', + description: null, + position: null, + content: 'Unreleased', + contentJson: null, + principalId: 'principal_1' as PrincipalId, + segmentIds: [], + publishedAt: null, + viewCount: 0, + helpfulCount: 0, + notHelpfulCount: 0, + urlId: 1, + createdAt: new Date('2026-01-01'), + updatedAt: new Date('2026-01-01'), + deletedAt: null, + category: { id: 'kb_category_1' as KbCategoryId, urlId: 1, slug: 'hidden', name: 'Hidden' }, + author: null, +} + +const hiddenCategory: HelpCenterCategory = { + id: 'kb_category_1' as KbCategoryId, + urlId: 1, + slug: 'hidden', + name: 'Hidden things', + description: null, + icon: null, + parentId: null, + isPublic: false, + segmentIds: [], + position: 0, + createdAt: new Date('2026-01-01'), + updatedAt: new Date('2026-01-01'), + deletedAt: null, +} as HelpCenterCategory + +const counted = (cat: HelpCenterCategory, n: number): HelpCenterCategoryWithCount => ({ + ...cat, + articleCount: n, + publishedArticleCount: n, + recursiveArticleCount: n, + recursivePublishedArticleCount: n, +}) + +const get = (url: string) => new Request(url, { method: 'GET' }) +const vote = () => + handlers(ArticleFeedbackRoute).POST({ + request: new Request('http://localhost/api/v1/help-center/articles/kb_article_1/feedback', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ helpful: true }), + }), + params: { articleId: 'kb_article_1' }, + }) + +beforeEach(() => { + vi.clearAllMocks() + vi.mocked(isFeatureEnabled).mockResolvedValue(true) + vi.mocked(getArticleById).mockResolvedValue(draft) + vi.mocked(getPublicArticleById).mockRejectedValue( + new NotFoundError('ARTICLE_NOT_FOUND', 'Article not found') + ) + vi.mocked(getCategoryById).mockResolvedValue(hiddenCategory) + vi.mocked(getPublicCategoryById).mockRejectedValue( + new NotFoundError('CATEGORY_NOT_FOUND', 'Category not found') + ) + const empty = { items: [], nextCursor: null, hasMore: false } + vi.mocked(listArticles).mockResolvedValue({ ...empty, items: [draft] }) + vi.mocked(listPublicArticles).mockResolvedValue(empty) + vi.mocked(listCategories).mockResolvedValue([counted(hiddenCategory, 1)]) + vi.mocked(listPublicCategories).mockResolvedValue([]) +}) + +describe('a key without help_center.manage', () => { + for (const [label, auth] of [ + ['a contributor key', contributor], + ['a read-scoped owner key', readOnlyOwner], + ] as const) { + it(`${label} is refused a draft article and never sees its title`, async () => { + vi.mocked(withApiKeyAuth).mockResolvedValue(auth) + const res = await handlers(ArticleDetailRoute).GET({ + request: get('http://localhost/api/v1/help-center/articles/kb_article_1'), + params: { articleId: 'kb_article_1' }, + }) + expect(res.status).toBe(403) + expect(await res.text()).not.toContain('Secret plan') + }) + + it(`${label} lists only the published public slice, whatever status it asks for`, async () => { + vi.mocked(withApiKeyAuth).mockResolvedValue(auth) + const res = await handlers(ArticlesListRoute).GET({ + request: get( + 'http://localhost/api/v1/help-center/articles?status=draft&categoryId=kb_category_1' + ), + }) + expect(res.status).toBe(200) + expect(await res.text()).not.toContain('Secret plan') + expect(listArticles).not.toHaveBeenCalled() + expect(listPublicArticles).toHaveBeenCalledWith( + expect.objectContaining({ categoryId: 'kb_category_1' }) + ) + }) + + it(`${label} lists only public categories`, async () => { + vi.mocked(withApiKeyAuth).mockResolvedValue(auth) + const res = await handlers(CategoriesListRoute).GET({ + request: get('http://localhost/api/v1/help-center/categories'), + }) + expect(res.status).toBe(200) + expect(await res.text()).not.toContain('Hidden things') + expect(listCategories).not.toHaveBeenCalled() + expect(listPublicCategories).toHaveBeenCalled() + }) + + it(`${label} is refused a private category and never sees its name`, async () => { + vi.mocked(withApiKeyAuth).mockResolvedValue(auth) + const res = await handlers(CategoryDetailRoute).GET({ + request: get('http://localhost/api/v1/help-center/categories/kb_category_1'), + params: { categoryId: 'kb_category_1' }, + }) + expect(res.status).toBe(403) + expect(await res.text()).not.toContain('Hidden things') + }) + } + + it('still reads a published public article', async () => { + vi.mocked(withApiKeyAuth).mockResolvedValue(contributor) + const published = { ...draft, title: 'Getting started', publishedAt: new Date('2026-01-02') } + vi.mocked(getArticleById).mockResolvedValue(published) + vi.mocked(getPublicArticleById).mockResolvedValue(published) + const res = await handlers(ArticleDetailRoute).GET({ + request: get('http://localhost/api/v1/help-center/articles/kb_article_1'), + params: { articleId: 'kb_article_1' }, + }) + expect(res.status).toBe(200) + expect(await res.text()).toContain('Getting started') + }) + + it('gets a 404, not a 403, for an article that does not exist', async () => { + vi.mocked(withApiKeyAuth).mockResolvedValue(contributor) + vi.mocked(getArticleById).mockRejectedValue( + new NotFoundError('ARTICLE_NOT_FOUND', 'Article not found') + ) + const res = await handlers(ArticleDetailRoute).GET({ + request: get('http://localhost/api/v1/help-center/articles/kb_article_1'), + params: { articleId: 'kb_article_1' }, + }) + expect(res.status).toBe(404) + }) +}) + +describe('voting over REST', () => { + it('refuses a vote on a draft from a key without help_center.manage', async () => { + vi.mocked(withApiKeyAuth).mockResolvedValue(contributor) + const res = await vote() + expect(res.status).toBe(403) + expect(recordArticleFeedback).not.toHaveBeenCalled() + }) + + it('answers 404, not 403, for an article that does not exist', async () => { + vi.mocked(withApiKeyAuth).mockResolvedValue(contributor) + vi.mocked(getArticleById).mockRejectedValue( + new NotFoundError('ARTICLE_NOT_FOUND', 'Article not found') + ) + const res = await vote() + expect(res.status).toBe(404) + expect(recordArticleFeedback).not.toHaveBeenCalled() + }) + + it('records a vote on a published public article', async () => { + vi.mocked(withApiKeyAuth).mockResolvedValue(contributor) + vi.mocked(getPublicArticleById).mockResolvedValue({ ...draft, publishedAt: new Date() }) + const res = await vote() + expect(res.status).toBe(200) + expect(recordArticleFeedback).toHaveBeenCalledWith('kb_article_1', true, 'principal_1') + }) + + it('lets a key with help_center.manage vote on a draft', async () => { + vi.mocked(withApiKeyAuth).mockResolvedValue(owner) + expect((await vote()).status).toBe(200) + }) +}) + +describe('the read:article scope', () => { + /** An owner's key scoped to feedback only: no help center reads at all. */ + const feedbackOnly = keyFor('owner', ['read:feedback', 'write:feedback']) + + it('is required for every help center read and vote', async () => { + vi.mocked(withApiKeyAuth).mockResolvedValue(feedbackOnly) + vi.mocked(getPublicArticleById).mockResolvedValue({ ...draft, publishedAt: new Date() }) + const responses = [ + await handlers(ArticlesListRoute).GET({ + request: get('http://localhost/api/v1/help-center/articles'), + }), + await handlers(ArticleDetailRoute).GET({ + request: get('http://localhost/api/v1/help-center/articles/kb_article_1'), + params: { articleId: 'kb_article_1' }, + }), + await handlers(CategoriesListRoute).GET({ + request: get('http://localhost/api/v1/help-center/categories'), + }), + await handlers(CategoryDetailRoute).GET({ + request: get('http://localhost/api/v1/help-center/categories/kb_category_1'), + params: { categoryId: 'kb_category_1' }, + }), + await vote(), + ] + expect(responses.map((r) => r.status)).toEqual([403, 403, 403, 403, 403]) + expect(listPublicArticles).not.toHaveBeenCalled() + expect(recordArticleFeedback).not.toHaveBeenCalled() + }) + + it('is enough on its own to read the public help center', async () => { + vi.mocked(withApiKeyAuth).mockResolvedValue(readOnlyOwner) + const res = await handlers(ArticlesListRoute).GET({ + request: get('http://localhost/api/v1/help-center/articles'), + }) + expect(res.status).toBe(200) + }) +}) + +describe('a key with help_center.manage', () => { + beforeEach(() => vi.mocked(withApiKeyAuth).mockResolvedValue(owner)) + + it('reads a draft article', async () => { + const res = await handlers(ArticleDetailRoute).GET({ + request: get('http://localhost/api/v1/help-center/articles/kb_article_1'), + params: { articleId: 'kb_article_1' }, + }) + expect(res.status).toBe(200) + expect(await res.text()).toContain('Secret plan') + expect(getPublicArticleById).not.toHaveBeenCalled() + }) + + it('lists drafts and private categories', async () => { + const articles = await handlers(ArticlesListRoute).GET({ + request: get('http://localhost/api/v1/help-center/articles?status=draft'), + }) + expect(await articles.text()).toContain('Secret plan') + expect(listArticles).toHaveBeenCalledWith(expect.objectContaining({ status: 'draft' })) + + const categories = await handlers(CategoriesListRoute).GET({ + request: get('http://localhost/api/v1/help-center/categories'), + }) + expect(await categories.text()).toContain('Hidden things') + }) + + it('reads a private category', async () => { + const res = await handlers(CategoryDetailRoute).GET({ + request: get('http://localhost/api/v1/help-center/categories/kb_category_1'), + params: { categoryId: 'kb_category_1' }, + }) + expect(res.status).toBe(200) + expect(await res.text()).toContain('Hidden things') + }) +}) diff --git a/apps/web/src/routes/api/v1/help-center/articles/$articleId.feedback.ts b/apps/web/src/routes/api/v1/help-center/articles/$articleId.feedback.ts index b7369fda54..f3594835c2 100644 --- a/apps/web/src/routes/api/v1/help-center/articles/$articleId.feedback.ts +++ b/apps/web/src/routes/api/v1/help-center/articles/$articleId.feedback.ts @@ -1,6 +1,10 @@ import { createFileRoute } from '@tanstack/react-router' import { z } from 'zod' import { withApiKeyAuth } from '@/lib/server/domains/api/auth' +import { + helpCenterApiAccess, + assertArticleOpenToKey, +} from '@/lib/server/domains/help-center/help-center-api-access' import { successResponse, badRequestResponse, @@ -24,9 +28,12 @@ export const Route = createFileRoute('/api/v1/help-center/articles/$articleId/fe if (!(await isFeatureEnabled('helpCenter'))) return notFoundResponse('Knowledge base') try { - const { principalId } = await withApiKeyAuth(request) + const access = helpCenterApiAccess(await withApiKeyAuth(request)) const articleId = parseTypeId(params.articleId, 'article', 'article ID') + // A key votes only on an article it may read: a draft, or an article + // in a private or gated category, needs help_center.manage. + await assertArticleOpenToKey(access, articleId) const body = await readJsonBody(request) const parsed = feedbackBody.safeParse(body) @@ -37,7 +44,11 @@ export const Route = createFileRoute('/api/v1/help-center/articles/$articleId/fe }) } - await recordArticleFeedback(articleId, parsed.data.helpful, principalId as PrincipalId) + await recordArticleFeedback( + articleId, + parsed.data.helpful, + access.auth.principalId as PrincipalId + ) return successResponse({ success: true }) } catch (error) { diff --git a/apps/web/src/routes/api/v1/help-center/articles/$articleId.ts b/apps/web/src/routes/api/v1/help-center/articles/$articleId.ts index 02465ae8c1..7cd93ea67c 100644 --- a/apps/web/src/routes/api/v1/help-center/articles/$articleId.ts +++ b/apps/web/src/routes/api/v1/help-center/articles/$articleId.ts @@ -1,6 +1,11 @@ import { createFileRoute } from '@tanstack/react-router' import { z } from 'zod' import { withApiKeyAuth } from '@/lib/server/domains/api/auth' +import { + helpCenterApiAccess, + assertArticleOpenToKey, +} from '@/lib/server/domains/help-center/help-center-api-access' + import { PERMISSIONS } from '@/lib/shared/permissions' import { successResponse, @@ -75,10 +80,13 @@ export const Route = createFileRoute('/api/v1/help-center/articles/$articleId')( if (!(await isFeatureEnabled('helpCenter'))) return notFoundResponse('Knowledge base') try { - await withApiKeyAuth(request) + const access = helpCenterApiAccess(await withApiKeyAuth(request)) const articleId = parseTypeId(params.articleId, 'article', 'article ID') + // A draft, or an article in a private or gated category, needs + // help_center.manage. + await assertArticleOpenToKey(access, articleId) const article = await getArticleById(articleId) return successResponse(formatArticle(article)) } catch (error) { diff --git a/apps/web/src/routes/api/v1/help-center/articles/index.ts b/apps/web/src/routes/api/v1/help-center/articles/index.ts index 1319da5bcb..466dee2feb 100644 --- a/apps/web/src/routes/api/v1/help-center/articles/index.ts +++ b/apps/web/src/routes/api/v1/help-center/articles/index.ts @@ -1,6 +1,7 @@ import { createFileRoute } from '@tanstack/react-router' import { z } from 'zod' import { withApiKeyAuth } from '@/lib/server/domains/api/auth' +import { helpCenterApiAccess } from '@/lib/server/domains/help-center/help-center-api-access' import { PERMISSIONS } from '@/lib/shared/permissions' import { successResponse, @@ -12,7 +13,11 @@ import { } from '@/lib/server/domains/api/responses' import { parseOptionalTypeId, parseTypeId } from '@/lib/server/domains/api/validation' import { isFeatureEnabled } from '@/lib/server/domains/settings/settings.service' -import { listArticles, createArticle } from '@/lib/server/domains/help-center/help-center.service' +import { + listArticles, + listPublicArticles, + createArticle, +} from '@/lib/server/domains/help-center/help-center.service' import { contentJsonToMarkdown } from '@/lib/server/markdown-tiptap' import type { TiptapContent } from '@/lib/server/db' import type { KbCategoryId, PrincipalId } from '@quackback/ids' @@ -70,7 +75,7 @@ export const Route = createFileRoute('/api/v1/help-center/articles/')({ if (!(await isFeatureEnabled('helpCenter'))) return notFoundResponse('Knowledge base') try { - await withApiKeyAuth(request) + const { manages } = helpCenterApiAccess(await withApiKeyAuth(request)) const url = new URL(request.url) const { limit } = parsePaginationParams(url) @@ -83,7 +88,11 @@ export const Route = createFileRoute('/api/v1/help-center/articles/')({ const status = (url.searchParams.get('status') as 'draft' | 'published' | 'all') ?? 'all' const search = url.searchParams.get('search') ?? undefined - const result = await listArticles({ categoryId, status, search, cursor, limit }) + // Drafts, private categories and gated articles are team material: + // a key without help_center.manage reads the published public slice. + const result = manages + ? await listArticles({ categoryId, status, search, cursor, limit }) + : await listPublicArticles({ categoryId, search, cursor, limit }) return successResponse(result.items.map(formatArticle), { pagination: { diff --git a/apps/web/src/routes/api/v1/help-center/categories/$categoryId.ts b/apps/web/src/routes/api/v1/help-center/categories/$categoryId.ts index 072a1e73f5..d91108dc4a 100644 --- a/apps/web/src/routes/api/v1/help-center/categories/$categoryId.ts +++ b/apps/web/src/routes/api/v1/help-center/categories/$categoryId.ts @@ -1,6 +1,11 @@ import { createFileRoute } from '@tanstack/react-router' import { z } from 'zod' import { withApiKeyAuth } from '@/lib/server/domains/api/auth' +import { + helpCenterApiAccess, + assertCategoryOpenToKey, +} from '@/lib/server/domains/help-center/help-center-api-access' + import { PERMISSIONS } from '@/lib/shared/permissions' import { successResponse, @@ -62,7 +67,7 @@ export const Route = createFileRoute('/api/v1/help-center/categories/$categoryId if (!(await isFeatureEnabled('helpCenter'))) return notFoundResponse('Knowledge base') try { - await withApiKeyAuth(request) + const access = helpCenterApiAccess(await withApiKeyAuth(request)) const categoryId = parseTypeId( params.categoryId, @@ -70,6 +75,8 @@ export const Route = createFileRoute('/api/v1/help-center/categories/$categoryId 'category ID' ) + // A private or gated category needs help_center.manage. + await assertCategoryOpenToKey(access, categoryId) const category = await getCategoryById(categoryId) return successResponse(formatCategory(category)) } catch (error) { diff --git a/apps/web/src/routes/api/v1/help-center/categories/index.ts b/apps/web/src/routes/api/v1/help-center/categories/index.ts index 5ad22f2904..855b3a80b6 100644 --- a/apps/web/src/routes/api/v1/help-center/categories/index.ts +++ b/apps/web/src/routes/api/v1/help-center/categories/index.ts @@ -1,6 +1,7 @@ import { createFileRoute } from '@tanstack/react-router' import { z } from 'zod' import { withApiKeyAuth } from '@/lib/server/domains/api/auth' +import { helpCenterApiAccess } from '@/lib/server/domains/help-center/help-center-api-access' import { PERMISSIONS } from '@/lib/shared/permissions' import { successResponse, @@ -12,6 +13,7 @@ import { import { isFeatureEnabled } from '@/lib/server/domains/settings/settings.service' import { listCategories, + listPublicCategories, createCategory, } from '@/lib/server/domains/help-center/help-center.service' import { readJsonBody } from '@/lib/server/domains/api/request' @@ -59,9 +61,12 @@ export const Route = createFileRoute('/api/v1/help-center/categories/')({ if (!(await isFeatureEnabled('helpCenter'))) return notFoundResponse('Knowledge base') try { - await withApiKeyAuth(request) + const { manages } = helpCenterApiAccess(await withApiKeyAuth(request)) - const categories = await listCategories() + // Private and gated categories, and counts that include drafts, are + // team material: a key without help_center.manage reads the public + // categories, counted by the articles everyone can open. + const categories = manages ? await listCategories() : await listPublicCategories() return successResponse( categories.map((cat) => ({ ...formatCategory(cat),