Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/weekly-social.yml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ jobs:
# Persist before sending. An uncertain send keeps its claim and cannot
# be retried automatically, including after a cancelled runner.
- name: Claim destination and week
id: claim
if: steps.prepare.outputs.eligible == 'true'
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
Expand All @@ -60,6 +61,7 @@ jobs:
if: steps.prepare.outputs.eligible == 'true'
run: pnpm exec tsx scripts/weekly-social.ts publish ${{ matrix.destination }}
env:
SKILLD_WEEKLY_CLAIM_ARTIFACT_ID: ${{ steps.claim.outputs.artifact-id }}
GH_TOKEN: ${{ github.token }}
SKILLD_WEEKLY_X_API_KEY: ${{ matrix.destination == 'x' && secrets.SKILLD_WEEKLY_X_API_KEY || '' }}
SKILLD_WEEKLY_X_API_SECRET: ${{ matrix.destination == 'x' && secrets.SKILLD_WEEKLY_X_API_SECRET || '' }}
Expand Down
12 changes: 7 additions & 5 deletions scripts/lib/weekly-social.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,14 @@ const detailSchema = z.object({
export const socialSkillSchema = feedRow.extend({ evidence: evidenceSchema, sourceUrl: detailSchema.shape.sourceUrl, runCommand: detailSchema.shape.runCommand })
export type SocialSkill = z.infer<typeof socialSkillSchema>

export function assertWeeklyClaim(value: unknown, runId: string): void {
const claims = z.object({
total_count: z.number().int().nonnegative(),
artifacts: z.array(z.object({ workflow_run: z.object({ id: z.number().int() }) })),
export function assertWeeklyClaim(value: unknown, expected: { artifactId: string, name: string, runId: string }): void {
const claim = z.object({
id: z.number().int().positive(),
name: z.string(),
expired: z.boolean(),
workflow_run: z.object({ id: z.number().int() }),
}).parse(value)
if (claims.total_count !== 1 || claims.artifacts.length !== 1 || String(claims.artifacts[0]?.workflow_run.id) !== runId)
if (String(claim.id) !== expected.artifactId || claim.name !== expected.name || claim.expired || String(claim.workflow_run.id) !== expected.runId)
throw new Error('This run does not own the weekly claim')
}

Expand Down
16 changes: 12 additions & 4 deletions scripts/weekly-social.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import { z } from 'zod'
import { assertWeeklyClaim, buildWeeklySocial, loadWeeklySocial, parseSocialDestination, publishWeeklySocial, socialSkillSchema, verifySocialDestination, weekOf } from './lib/weekly-social'

/** GitHub's artifact service persists the claim before any public send. */
async function weeklyClaims(name: string): Promise<unknown> {
async function weeklyClaims(query: { name: string } | { artifactId: string }): Promise<unknown> {
const repository = z.string().regex(/^[\w.-]+\/[\w.-]+$/).parse(process.env.GITHUB_REPOSITORY)
const token = z.string().min(1).parse(process.env.GH_TOKEN)
const response = await fetch(`https://api.github.com/repos/${repository}/actions/artifacts?name=${encodeURIComponent(name)}&per_page=100`, {
const path = 'artifactId' in query ? `/${query.artifactId}` : `?name=${encodeURIComponent(query.name)}&per_page=100`
const response = await fetch(`https://api.github.com/repos/${repository}/actions/artifacts${path}`, {
headers: { 'authorization': `Bearer ${token}`, 'accept': 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' },
redirect: 'error',
signal: AbortSignal.timeout(30_000),
Expand Down Expand Up @@ -37,7 +38,14 @@ async function run() {
const saved = z.object({ week: z.string(), computedAt: z.number(), skills: z.array(socialSkillSchema) }).parse(JSON.parse(await readFile(path, 'utf8')))
if (saved.week !== weekOf(now) || now.getTime() / 1000 - saved.computedAt > 3600)
throw new Error('Prepare a fresh weekly post before publishing')
assertWeeklyClaim(await weeklyClaims(`skilld-weekly-${destinationName}-${saved.week}`), z.string().regex(/^\d+$/).parse(process.env.GITHUB_RUN_ID))
// The prepare lookup can remain cached for 60 seconds after upload.
// Read the uploaded artifact directly instead of repeating that list request.
const artifactId = z.string().regex(/^\d+$/).parse(process.env.SKILLD_WEEKLY_CLAIM_ARTIFACT_ID)
assertWeeklyClaim(await weeklyClaims({ artifactId }), {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Minor (78/100): A stale prepare lookup can allow duplicate weekly posts

If a queued or manually dispatched run gets a stale zero-count result from the prepare lookup after a prior run has sent, it can upload another artifact with the same destination and week. GitHub permits the same artifact name in separate runs. The destination lock serializes the jobs, but the new publish check accepts each run's own artifact and no longer requires a unique claim. Both runs can post publicly.

Require a fresh name lookup for prior claims before uploading under the existing destination lock, and keep the direct artifact check before sending.

  • Ask an agent to verify and fix this finding

Harlan Agent Kit posted this automated review. It is not Harlan's personal review or approval. AI open source policy.

artifactId,
name: `skilld-weekly-${destinationName}-${saved.week}`,
runId: z.string().regex(/^\d+$/).parse(process.env.GITHUB_RUN_ID),
})
const result = await publishWeeklySocial(parseSocialDestination(destinationName, process.env), buildWeeklySocial(saved.skills, now))
console.log(JSON.stringify(result))
await writeFile(join(directory, 'receipt.json'), `${JSON.stringify(result, null, 2)}\n`)
Expand All @@ -56,7 +64,7 @@ async function run() {
await appendFile(process.env.GITHUB_STEP_SUMMARY, `### ${destinationName}: ${post.week}\n\n\`\`\`json\n${preview}\n\`\`\`\n`)

let eligible = post._tag === 'ready' && publishing
if (eligible && z.object({ total_count: z.number().int().nonnegative() }).parse(await weeklyClaims(claim)).total_count > 0) {
if (eligible && z.object({ total_count: z.number().int().nonnegative() }).parse(await weeklyClaims({ name: claim })).total_count > 0) {
eligible = false
console.log('This destination already has a weekly delivery claim. Inspect its previous run before retrying.')
}
Expand Down
16 changes: 11 additions & 5 deletions test/unit/weekly-social.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ describe('weekly social posts', () => {

describe('posting identity', () => {
const credentials = { consumerKey: 'key', consumerSecret: 'secret', accessToken: 'token', accessSecret: 'token-secret' }
const claim = { id: 14861832971, name: 'skilld-weekly-discord-2026-11-23', expired: false, workflow_run: { id: 45264333491 } }
const expectedClaim = { artifactId: String(claim.id), name: claim.name, runId: String(claim.workflow_run.id) }
it('signs the RFC 5849 reference request', () => {
const header = oauthHeader('GET', 'http://photos.example.net/photos?file=vacation.jpg&size=original', {
consumerKey: 'dpf43f3p2l4k3l03',
Expand All @@ -122,10 +124,11 @@ describe('posting identity', () => {
await expect(verifySocialDestination({ _tag: 'discord', webhookUrl: 'https://discord.com/api/webhooks/1/token', channelId: '2' }, fetchImpl)).rejects.toThrow('Discord webhook belongs to another server or channel')
})

it('publishes to the checked Discord channel and returns its confirmed message ID', async () => {
it('publishes with the uploaded claim and returns the checked Discord channel message ID', async () => {
const fetchImpl = vi.fn<typeof fetch>()
.mockResolvedValueOnce(Response.json({ guild_id: '931135234261532713', channel_id: '2' }))
.mockResolvedValueOnce(Response.json({ id: '123' }))
assertWeeklyClaim(claim, expectedClaim)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Trivial (35/100): Publish test bypasses artifact lookup and claim enforcement

The test calls assertWeeklyClaim with a hard-coded artifact, then calls publishWeeklySocial separately. It never exercises the publishing command that reads the upload output and fetches the artifact. The test would still pass if that command ignored the artifact ID, used the list endpoint, or skipped claim verification.

Add a publish-entry-point test that verifies the artifact request and blocks the destination POST for a mismatched claim.

  • Ask an agent to verify and fix this finding

Harlan Agent Kit posted this automated review. It is not Harlan's personal review or approval. AI open source policy.

const result = await publishWeeklySocial({ _tag: 'discord', webhookUrl: 'https://discord.com/api/webhooks/1/token', channelId: '2' }, buildWeeklySocial([skill], now), fetchImpl)
expect(result).toEqual({ _tag: 'sent', id: '123' })
expect(fetchImpl.mock.calls[1]?.[0]).toBe('https://discord.com/api/webhooks/1/token?wait=true')
Expand All @@ -140,9 +143,12 @@ describe('posting identity', () => {
expect(fetchImpl).toHaveBeenCalledTimes(2)
})

it('requires a persisted claim owned by this run before sending', () => {
expect(() => assertWeeklyClaim({ total_count: 0, artifacts: [] }, '42')).toThrow('This run does not own the weekly claim')
expect(() => assertWeeklyClaim({ total_count: 1, artifacts: [{ workflow_run: { id: 41 } }] }, '42')).toThrow('This run does not own the weekly claim')
assertWeeklyClaim({ total_count: 1, artifacts: [{ workflow_run: { id: 42 } }] }, '42')
it.each([
{ ...claim, id: 14861832972 },
{ ...claim, name: 'skilld-weekly-x-2026-11-23' },
{ ...claim, expired: true },
{ ...claim, workflow_run: { id: 45264333490 } },
])('rejects a claim that does not match the upload, week, destination, or run: %j', (artifact) => {
expect(() => assertWeeklyClaim(artifact, expectedClaim)).toThrow('This run does not own the weekly claim')
})
})
Loading