Skip to content
Open
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
141 changes: 141 additions & 0 deletions .github/workflows/create-songbook-post.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
name: Create Songbook Post

on:
workflow_dispatch:
inputs:
filename:
description: "Filename / Slug for the post (e.g. bukayo-saka)"
required: true
type: string
title:
description: "Post Title (Optional if imageAlt provided)"
required: false
type: string
date:
description: "Post Date in YYYY-MM-DD format (Optional)"
required: false
type: string
image:
description: "Image URL (Required, e.g. https://example.com/image.jpg)"
required: true
type: string
imageAlt:
description: "Image Alt text (Optional if title provided)"
required: false
type: string
imageDimensions:
description: "Image dimensions WxH (Required, e.g. 735x990)"
required: true
type: string
imagePlacement:
description: 'Image placement (Required, e.g. header, body, or JSON: {"all":"header","md":"body"})'
required: true
default: "header"
type: string
imageLink:
description: "Image link URL (Optional)"
required: false
type: string
orientation:
description: "Image orientation (Optional, e.g. portrait, landscape, square, banner)"
required: false
type: string
metaTitle:
description: "Meta Title for SEO (Optional)"
required: false
type: string
additionalStyling:
description: "Additional CSS styling class (Optional)"
required: false
type: string
content:
description: "Post Markdown / Song Lyrics content (Optional)"
required: false
type: string
imageFileName:
description: "Filename to save the downloaded image in public/ (e.g. my-image.jpg)"
required: true
type: string
branch:
description: "The branch to run on"
required: true
default: "main"
type: string
Comment on lines +59 to +63

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -eo pipefail

echo "== file exists =="
git ls-files | grep -FxF ".github/workflows/create-songbook-post.yml" || true

echo "== diff stat =="
git diff --stat # from HEAD if possible

echo "== workflow relevant sections =="
if [ -f .github/workflows/create-songbook-post.yml ]; then
  nl -ba .github/workflows/create-songbook-post.yml | sed -n '1,130p'
fi

echo "== find create-pull-request and automation key usages =="
rg -n "create-pull-request|DATA_PIPELINE_PR_AUTOMATION_KEY|pull_request_token|persist-credentials|actions/checkout|branch:" .github/workflows . -g '!node_modules' -g '!dist' -g '!build' | head -200

Repository: jtzero/cle-gunners

Length of output: 307


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== workflow relevant sections =="
awk '{printf "%6d  %s\n", NR, $0}' .github/workflows/create-songbook-post.yml | sed -n '1,140p'

echo "== focused search =="
grep -RInE 'create-pull-request|DATA_PIPELINE_PR_AUTOMATION_KEY|pull_request_token|persist-credentials|actions/checkout|inputs\.branch|refs/heads|github.ref' .github/workflows . -g '!node_modules' -g '!dist' -g '!build' | head -200

echo "== package scripts =="
if [ -f package.json ]; then
  python3 - <<'PY'
import json
with open("package.json") as f:
    data=json.load(f)
print({k:data.get(k) for k in ("scripts","dependencies","devDependencies")})
PY
fi

Repository: jtzero/cle-gunners

Length of output: 5423


🌐 Web query:

GitHub Actions workflow_dispatch user permissions write access required

💡 Result:

To manually trigger a GitHub Actions workflow using the workflow_dispatch event, write access to the repository is required [1][2][3]. Key details regarding permissions and requirements: 1. Repository Access: Users or service accounts (via tokens) must have write access to the repository to trigger a workflow manually via the GitHub UI, GitHub CLI, or REST API [1][4][3]. 2. Workflow Location: The workflow file must exist on the repository's default branch for the workflow_dispatch trigger to be active and recognized by GitHub [1][5][3]. 3. Authentication Scopes: When using API tokens (Personal Access Tokens or OAuth tokens), the required permissions typically involve repository write access (often represented by the repo scope for classic tokens) or specific fine-grained permissions such as actions:write [6][4][7]. 4. UI Visibility: If a user does not have write access, they will not see the Run workflow button in the GitHub Actions tab, even if the workflow is properly configured [1][2]. In summary, write access is a fundamental requirement for manually invoking workflows configured with workflow_dispatch, as it ensures only authorized users can initiate these actions [1][2][3].

Citations:


🌐 Web query:

npm install runs lifecycle scripts install lifecycle documentation

💡 Result:

In npm, lifecycle scripts are automated hooks defined in the scripts property of a package.json file that execute at specific stages of package installation and management [1][2][3]. As of July 2026, with the release of npm v12, significant security changes have been implemented regarding these scripts [4]. Lifecycle Scripts and npm install When running npm install, the following lifecycle scripts are standard: - preinstall: Executes before the package is installed [3][4]. - install: Executes after the package is installed [3][4]. - postinstall: Executes after the package is installed [3][4]. Important Security Change (npm v12+) Prior to npm v12, these scripts executed automatically by default, posing significant supply chain security risks [5][6][4]. Starting with npm v12 (released July 2026), all dependency install scripts are disabled by default [4]. Furthermore, this protection now extends to the implicit node-gyp rebuild process (triggered by binding.gyp files), which previously acted as a "Phantom Gyp" bypass for security controls [4]. Packages that require these scripts must now be explicitly allowlisted in the project's npm configuration [7][4]. Execution Order During an npm install command, the lifecycle scripts for the project and its dependencies typically follow this general sequence [3]: 1. preinstall 2. install 3. postinstall 4. prepublish 5. preprepare 6. prepare 7. postprepare Note that recent updates have refined the execution of root-level preinstall scripts to ensure they run before dependency resolution (reify) begins, addressing long-standing issues where root scripts could not effectively gate the installation process [8]. Management and Environment Variables - Environment Variable: The npm_lifecycle_event environment variable is set during execution, allowing a single script to detect which lifecycle stage is currently active [1][9][2]. - Best Practices: Users should avoid relying on automatic script execution for critical build steps and should instead use explicit, controlled build processes [5][10]. Reviewing the hasInstallScript flag in package-lock.json is recommended for identifying dependencies that utilize these hooks [4].

Citations:


Do not run dispatcher-selected refs with the automation key.

workflow_dispatch requires write access, and this job checks out $inputs.branch with DATA_PIPELINE_PR_AUTOMATION_KEY before npm install. Even if root install scripts are disabled, selected repository code can still execute with that credential and expose it. Remove the branch input, checkout main, use the scoped GITHUB_TOKEN, and set persist-credentials: false. If non-main refs are required, run them in a separate job without write permissions or secrets.

🤖 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 @.github/workflows/create-songbook-post.yml around lines 55 - 59, Remove the
workflow_dispatch branch input and update the job to always check out main.
Replace DATA_PIPELINE_PR_AUTOMATION_KEY with the scoped GITHUB_TOKEN for
checkout, and set persist-credentials: false so credentials are not retained;
handle any non-main refs only in a separate job without write permissions or
secrets.

Source: Linters/SAST tools


jobs:
create-songbook-post:
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write

steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
ssh-key: ${{ secrets.DATA_PIPELINE_PR_AUTOMATION_KEY }}
ref: ${{ inputs.branch }}

- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "20"
cache: "npm"

- name: Install dependencies
run: npm install

- name: Download image
run: |
mkdir -p public
IMAGE_PATH="public/${{ inputs.imageFileName }}"
mkdir -p "$(dirname "$IMAGE_PATH")"
curl -L -o "$IMAGE_PATH" ${{ inputs.image }}

- name: Create Songbook Post
env:
INPUT_FILENAME: ${{ inputs.filename }}
INPUT_TITLE: ${{ inputs.title }}
INPUT_DATE: ${{ inputs.date }}
INPUT_IMAGE: /${{ inputs.imageFileName }}
INPUT_IMAGE_ALT: ${{ inputs.imageAlt }}
INPUT_IMAGE_DIMENSIONS: ${{ inputs.imageDimensions }}
INPUT_IMAGE_PLACEMENT: ${{ inputs.imagePlacement }}
INPUT_IMAGE_LINK: ${{ inputs.imageLink }}
INPUT_ORIENTATION: ${{ inputs.orientation }}
INPUT_META_TITLE: ${{ inputs.metaTitle }}
INPUT_ADDITIONAL_STYLING: ${{ inputs.additionalStyling }}
INPUT_CONTENT: ${{ inputs.content }}
run: npm run create-songbook-post

- name: Format generated post
run: npm run format

- name: Run unit tests
run: npm run test:unit

- name: Log git status
run: git status

- name: Create Pull Request
id: cpr
uses: peter-evans/create-pull-request@v7
with:
commit-message: "feat(songbook): add songbook post ${{ inputs.filename }}"
branch: "songbook-post-${{ inputs.filename }}"
base: "main"
add-paths: |
src/content/posts/*
public/${{ inputs.imageFileName }}
title: "New Songbook Post: ${{ inputs.title || inputs.filename }}"
body: |
This is an automated pull request to create a new songbook post using `imagePost` schema inputs.
labels: |
songbook-post

- name: Enable Pull Request Automerge
if: steps.cpr.outputs.pull-request-number != ''
run: |
gh pr merge --rebase --auto "${{ steps.cpr.outputs.pull-request-number }}"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
43 changes: 43 additions & 0 deletions bin/create-songbook-post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import {
createSongbookPostFile,
type SongbookPostInput,
} from "@/lib/createSongbookPost";

const input: SongbookPostInput = {
filename: process.env.INPUT_FILENAME || process.argv[2] || "",
title: process.env.INPUT_TITLE || undefined,
date: process.env.INPUT_DATE || undefined,
image: process.env.INPUT_IMAGE || process.argv[3] || "",
imageAlt: process.env.INPUT_IMAGE_ALT || undefined,
imageDimensions: process.env.INPUT_IMAGE_DIMENSIONS || process.argv[4] || "",
imagePlacement:
process.env.INPUT_IMAGE_PLACEMENT || process.argv[5] || "header",
imageLink: process.env.INPUT_IMAGE_LINK || undefined,
orientation: process.env.INPUT_ORIENTATION || undefined,
metaTitle: process.env.INPUT_META_TITLE || undefined,
additionalStyling: process.env.INPUT_ADDITIONAL_STYLING || undefined,
content: process.env.INPUT_CONTENT || undefined,
};

if (!input.filename) {
console.error("Error: 'filename' input is required.");
process.exit(1);
}

if (!input.image) {
console.error("Error: 'image' input is required.");
process.exit(1);
}

if (!input.imageDimensions) {
console.error("Error: 'imageDimensions' input is required.");
process.exit(1);
}

try {
const result = createSongbookPostFile(input);
console.log(`Successfully created songbook post at: ${result.filePath}`);
} catch (error) {
console.error("Error creating songbook post:", error);
process.exit(1);
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"check": "astro check && prettier --check .",
"format": "prettier --write .",
"get-data": "tsx bin/get-data.ts",
"create-songbook-post": "tsx bin/create-songbook-post.ts",
"test": "vitest run --exclude \"**/*.integration.test.ts\"",
"test:unit": "npm run test",
"test:integration": "vitest run integration",
Expand Down
113 changes: 113 additions & 0 deletions src/lib/createSongbookPost.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import fs from "fs";
import path from "path";
import os from "os";
import { describe, expect, test } from "vitest";
import {
generateSongbookPostMarkdown,
createSongbookPostFile,
parseImagePlacement,
} from "./createSongbookPost";
import { postSchema } from "@/content.types";

describe("createSongbookPost", () => {
describe("parseImagePlacement", () => {
test("parses plain string placement", () => {
expect(parseImagePlacement("header")).toBe("header");
expect(parseImagePlacement("body")).toBe("body");
});

test("parses valid JSON object placement", () => {
const result = parseImagePlacement('{"all":"header","md":"body"}');
expect(result).toEqual({ all: "header", md: "body" });
});

test("falls back to raw string when JSON is invalid", () => {
const result = parseImagePlacement("{invalid json}");
expect(result).toBe("{invalid json}");
});
});

describe("generateSongbookPostMarkdown", () => {
test("generates markdown compliant with imagePost schema", () => {
const markdown = generateSongbookPostMarkdown({
filename: "saka-chant",
title: "Bukayo Saka",
image: "/images/saka.jpg",
imageDimensions: "735x990",
imagePlacement: "header",
orientation: "portrait",
content: "We've got Bukayo Saka...",
});

expect(markdown).toContain('title: "Bukayo Saka"');
expect(markdown).toContain('image: "/images/saka.jpg"');
expect(markdown).toContain('imageDimensions: "735x990"');
expect(markdown).toContain("imagePlacement: header");
expect(markdown).toContain("We've got Bukayo Saka...");
});

test("supports imagePlacement as responsive JSON object", () => {
const markdown = generateSongbookPostMarkdown({
filename: "rice-chant",
title: "Declan Rice",
image: "/images/rice.jpg",
imageDimensions: "1242x828",
imagePlacement: '{"all":"header","md":"body"}',
imageAlt: "Declan Rice celebrating",
content: "Declan Rice...",
});

expect(markdown).toContain("imagePlacement:");
expect(markdown).toContain(" all: header");
expect(markdown).toContain(" md: body");
expect(markdown).toContain('imageAlt: "Declan Rice celebrating"');
});

test("throws error if inputs fail imagePost schema validation", () => {
expect(() => {
generateSongbookPostMarkdown({
filename: "invalid-post",
image: "/images/test.jpg",
imageDimensions: "100x100",
imagePlacement: "header",
// Missing both title and imageAlt
});
}).toThrowError(/Validation failed for imagePost schema/);
});
});

describe("createSongbookPostFile", () => {
test("creates songbook post file in target directory", () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "songbook-test-"));
try {
const result = createSongbookPostFile(
{
filename: "saliba-chant",
title: "William Saliba",
image: "/images/saliba.jpg",
imageDimensions: "500x500",
imagePlacement: "body",
content: "Te-quila!",
},
tmpDir,
);

const expectedPath = path.join(
tmpDir,
"src",
"content",
"posts",
"saliba-chant.md",
);
expect(result.filePath).toBe(expectedPath);
expect(fs.existsSync(expectedPath)).toBe(true);

const writtenContent = fs.readFileSync(expectedPath, "utf-8");
expect(writtenContent).toContain('title: "William Saliba"');
expect(writtenContent).toContain("Te-quila!");
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
});
});
});
Loading
Loading