From 8babff0cb44e11fde4dac0c6685b9f4d6f80eb11 Mon Sep 17 00:00:00 2001 From: NathanWalker Date: Sun, 22 Nov 2026 11:16:10 -0800 Subject: [PATCH] feat(cla): add org-wide GitHub Actions CLA workflow, legal docs, and signer sync --- .github/PULL_REQUEST_TEMPLATE.md | 24 ++ .github/workflows/cla.yml | 661 +++++++++++++++++++++++++++++ .github/workflows/sync-org-cla.yml | 182 ++++++++ .github/workflows/test-cla.yml | 38 ++ CLA.md | 71 ++++ CONTRIBUTING.md | 4 +- docs/legal/corporate-cla.md | 20 + docs/legal/individual-cla.md | 55 +++ scripts/check-cla.mjs | 507 ++++++++++++++++++++++ scripts/check-cla.test.mjs | 262 ++++++++++++ scripts/github-api-retry.cjs | 86 ++++ 11 files changed, 1908 insertions(+), 2 deletions(-) create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/workflows/cla.yml create mode 100644 .github/workflows/sync-org-cla.yml create mode 100644 .github/workflows/test-cla.yml create mode 100644 CLA.md create mode 100644 docs/legal/corporate-cla.md create mode 100644 docs/legal/individual-cla.md create mode 100644 scripts/check-cla.mjs create mode 100644 scripts/check-cla.test.mjs create mode 100644 scripts/github-api-retry.cjs diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..07c9296 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,24 @@ + + + + + +## PR Checklist + +- [ ] The PR title follows our guidelines: https://github.com/NativeScript/NativeScript/blob/main/tools/notes/CONTRIBUTING.md#commit-messages. +- [ ] There is an issue for the bug/feature this PR is for. To avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it. +- [ ] You have read and signed the [CLA](https://github.com/NativeScript/.github/blob/master/CLA.md) (first-time contributors can sign directly on the PR by commenting `I have read the CLA and I hereby sign the CLA`). +- [ ] All existing tests are passing. +- [ ] Tests for the changes are included where applicable. + +## What is the current behavior? + + +## What is the new behavior? + + +Fixes/Implements/Closes #[Issue Number]. diff --git a/.github/workflows/cla.yml b/.github/workflows/cla.yml new file mode 100644 index 0000000..f0c2f5b --- /dev/null +++ b/.github/workflows/cla.yml @@ -0,0 +1,661 @@ +name: โœ๏ธ CLA + +on: + workflow_call: + # pull_request_target (never pull_request): fork PRs get a read-only GITHUB_TOKEN + # on pull_request, which cannot post signing instructions. These jobs never check + # out or execute PR head code. + pull_request_target: + types: + - opened + - reopened + - synchronize + - closed + issue_comment: + types: + - created + - edited + - deleted + workflow_dispatch: + +permissions: + contents: read + +jobs: + cla: + if: >- + github.event_name == 'pull_request_target' && + github.event.action != 'closed' + runs-on: ubuntu-latest + name: โœ๏ธ CLA + timeout-minutes: 5 + permissions: + contents: read + pull-requests: write + steps: + - name: ๐Ÿ“ฆ Checkout CLA hub + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: NativeScript/.github + ref: master + path: cla-hub + persist-credentials: false + + - name: ๐Ÿ“œ Checkout org CLA signatures + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: NativeScript/.github + ref: cla-signatures + path: org-cla-signatures + persist-credentials: false + + - name: ๐ŸŸข Setup Node + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: '24' + + - name: ๐Ÿงพ Collect identities and comments + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + with: + script: | + const fs = require('node:fs/promises'); + const pullNumber = Number(process.env.PR_NUMBER); + const owner = context.repo.owner; + const repo = context.repo.repo; + + // Load repo-local cla-signatures if this repository has recorded signers not yet swept org-wide + if (`${owner}/${repo}`.toLowerCase() !== 'nativescript/.github') { + try { + const localRes = await github.rest.repos.getContent({ + owner, + repo, + path: 'cla-signers.json', + ref: 'cla-signatures', + }); + if (localRes.data && 'content' in localRes.data && localRes.data.content) { + const decoded = Buffer.from(localRes.data.content, 'base64').toString('utf8'); + await fs.writeFile('local-cla-signers.json', decoded, 'utf8'); + } + } catch (err) { + if (err.status !== 404) { + core.info(`No repo-local cla-signatures loaded (${err.status ?? err.message}).`); + } + } + } + + const identities = [ + { + githubLogin: context.payload.pull_request.user.login, + name: context.payload.pull_request.user.login, + email: null, + }, + ]; + const commits = await github.paginate( + github.rest.pulls.listCommits, + { + owner, + repo, + pull_number: pullNumber, + per_page: 100, + }, + ); + for (const commit of commits) { + identities.push({ + githubLogin: commit.author?.login ?? null, + name: commit.commit.author?.name ?? null, + email: commit.commit.author?.email ?? null, + }); + } + + const comments = await github.paginate( + github.rest.issues.listComments, + { + owner, + repo, + issue_number: pullNumber, + per_page: 100, + }, + ); + const signingComments = comments + .filter((comment) => comment.user?.type === 'User') + .map((comment) => ({ + login: comment.user.login, + createdAt: comment.created_at, + body: comment.body ?? '', + })); + + // Cross-repo instant fallback: if an identity is not yet in org-cla-signatures + // and has not commented on this PR, check if they already signed on a merged PR + // anywhere in org:NativeScript before the hourly org sync runs. + const orgRaw = JSON.parse(await fs.readFile('org-cla-signatures/cla-signers.json', 'utf8')); + const knownSet = new Set([ + ...orgRaw.allowlist.github.map((s) => s.trim().toLowerCase()), + ...orgRaw.signers.map((s) => s.github.trim().toLowerCase()), + ]); + const phrase = 'I have read the CLA and I hereby sign the CLA'; + for (const sc of signingComments) { + if (sc.body.trim() === phrase) { + knownSet.add(sc.login.trim().toLowerCase()); + } + } + + const candidateLogins = new Set(); + for (const id of identities) { + if (!id.githubLogin) continue; + const low = id.githubLogin.trim().toLowerCase(); + if (low.endsWith('[bot]') || low.startsWith('app/') || knownSet.has(low)) continue; + candidateLogins.add(id.githubLogin.trim()); + } + + for (const login of candidateLogins) { + try { + const searchRes = await github.rest.search.issuesAndPullRequests({ + q: `org:${owner} is:pr is:merged commenter:${login} "${phrase}"`, + per_page: 5, + }); + for (const item of searchRes.data.items) { + const repoParts = item.repository_url.split('/'); + const itemRepo = repoParts.at(-1); + const itemOwner = repoParts.at(-2); + const prComments = await github.paginate( + github.rest.issues.listComments, + { + owner: itemOwner, + repo: itemRepo, + issue_number: item.number, + per_page: 100, + }, + ); + const match = prComments.find( + (c) => + c.user?.type === 'User' && + c.user?.login?.toLowerCase() === login.toLowerCase() && + (c.body ?? '').trim() === phrase, + ); + if (match) { + signingComments.push({ + login: match.user.login, + createdAt: match.created_at, + body: match.body ?? '', + }); + break; + } + } + } catch (err) { + core.info(`Cross-repo signing search skipped for @${login}: ${err.message}`); + } + } + + await fs.writeFile( + 'cla-identities.json', + `${JSON.stringify(identities, null, '\t')}\n`, + ); + await fs.writeFile( + 'cla-signing-comments.json', + `${JSON.stringify(signingComments, null, '\t')}\n`, + ); + + - name: โœ๏ธ Check CLA + id: check + run: | + check_args=( + --signers org-cla-signatures/cla-signers.json + --identities-json cla-identities.json + --signing-comments-json cla-signing-comments.json + --missing-json cla-missing.json + ) + if [ -f local-cla-signers.json ]; then + check_args+=(--extra-signers local-cla-signers.json) + fi + set +e + node cla-hub/scripts/check-cla.mjs "${check_args[@]}" + code=$? + echo "exit_code=$code" >> "$GITHUB_OUTPUT" + if [ "$code" -ne 0 ] && [ "$code" -ne 1 ]; then + exit "$code" + fi + + - name: ๐Ÿ’ฌ Comment when unsigned + if: steps.check.outputs.exit_code == '1' + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + with: + script: | + const fs = require('node:fs/promises'); + const missing = JSON.parse(await fs.readFile('cla-missing.json', 'utf8')); + const marker = ''; + const missingLines = missing.map((entry) => `- ${entry.reason}`); + const body = [ + marker, + 'Unsigned contributions cannot merge.', + '', + '1. Read the [Individual CLA](https://github.com/NativeScript/.github/blob/master/docs/legal/individual-cla.md) (or the [Corporate CLA](https://github.com/NativeScript/.github/blob/master/docs/legal/corporate-cla.md) if an organization owns the work).', + '2. Comment exactly: `I have read the CLA and I hereby sign the CLA`', + '3. That signing comment satisfies this check across all `NativeScript` repositories. The signer is recorded on the [`cla-signatures`](https://github.com/NativeScript/.github/blob/cla-signatures/cla-signers.json) branch after this pull request merges. See the [CLA guide](https://github.com/NativeScript/.github/blob/master/CLA.md).', + ...(missingLines.length > 0 ? ['', '**Missing CLA status:**', ...missingLines] : []), + '', + 'Adding your own username on this branch does not pass the check.', + ].join('\n'); + + const comments = await github.paginate( + github.rest.issues.listComments, + { + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.payload.pull_request.number, + per_page: 100, + }, + ); + const existing = comments.find((comment) => + comment.body?.includes(marker), + ); + if (existing) { + await github.rest.issues.updateComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: existing.id, + body, + }); + } else { + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.payload.pull_request.number, + body, + }); + } + + - name: โœ… Update prior unsigned comment when now signed + if: steps.check.outputs.exit_code == '0' + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + with: + script: | + const marker = ''; + const comments = await github.paginate( + github.rest.issues.listComments, + { + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.payload.pull_request.number, + per_page: 100, + }, + ); + const existing = comments.find((comment) => + comment.body?.includes(marker), + ); + if (existing && !existing.body.includes('โœ… All contributors')) { + const body = [ + marker, + 'โœ… All contributors on this pull request have satisfied the [NativeScript CLA](https://github.com/NativeScript/.github/blob/master/CLA.md).', + ].join('\n'); + await github.rest.issues.updateComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: existing.id, + body, + }); + } + + - name: โŒ Fail when unsigned + if: steps.check.outputs.exit_code == '1' + run: exit 1 + + record: + if: >- + github.event_name == 'issue_comment' && + github.event.issue.pull_request != null && + github.event.comment.user.type == 'User' && + ( + contains(github.event.comment.body, 'I hereby sign the CLA') || + ( + github.event.action == 'edited' && + contains(github.event.changes.body.from, 'I hereby sign the CLA') + ) + ) + runs-on: ubuntu-latest + name: ๐Ÿ“ Record CLA + timeout-minutes: 5 + permissions: + pull-requests: write + actions: write + steps: + - name: ๐Ÿ’ฌ Acknowledge signature and re-run CLA + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + env: + PR_NUMBER: ${{ github.event.issue.number }} + CLA_LOGIN: ${{ github.event.comment.user.login }} + COMMENT_ACTION: ${{ github.event.action }} + with: + script: | + const login = process.env.CLA_LOGIN; + const action = process.env.COMMENT_ACTION; + const commentBody = context.payload.comment.body ?? ''; + const isSigning = + action !== 'deleted' && + commentBody.trim() === 'I have read the CLA and I hereby sign the CLA'; + const pullNumber = Number(process.env.PR_NUMBER); + const owner = context.repo.owner; + const repo = context.repo.repo; + const pull = await github.rest.pulls.get({ + owner, + repo, + pull_number: pullNumber, + }); + const headSha = pull.data.head.sha; + + async function latestClaRun() { + const runs = await github.rest.actions.listWorkflowRuns({ + owner, + repo, + workflow_id: 'cla.yml', + event: 'pull_request_target', + head_sha: headSha, + per_page: 5, + }); + return ( + runs.data.workflow_runs.find( + (run) => + run.status !== 'completed' || run.conclusion !== 'skipped', + ) ?? null + ); + } + + const deadline = Date.now() + 180_000; + let latest = await latestClaRun(); + while (latest && latest.status !== 'completed' && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 10_000)); + latest = await latestClaRun(); + } + + let reran = false; + if (latest?.status === 'completed') { + try { + await github.rest.actions.reRunWorkflow({ + owner, + repo, + run_id: latest.id, + }); + reran = true; + } catch (error) { + core.warning( + `Could not re-run CLA: ${error instanceof Error ? error.message : String(error)}`, + ); + } + } + + if (isSigning) { + const marker = ``; + const followUp = reran + ? 'The CLA check will re-run.' + : 'The CLA check will include this signing comment on its next run.'; + const body = [ + marker, + `Thanks @${login} โ€” your signature on this PR satisfies the CLA check, and you'll be recorded on the \`cla-signatures\` branch after this PR merges. ${followUp}`, + ].join('\n'); + + const comments = await github.paginate( + github.rest.issues.listComments, + { + owner, + repo, + issue_number: pullNumber, + per_page: 100, + }, + ); + const existing = comments.find((comment) => + comment.body?.includes(marker), + ); + if (existing) { + await github.rest.issues.updateComment({ + owner, + repo, + comment_id: existing.id, + body, + }); + } else { + await github.rest.issues.createComment({ + owner, + repo, + issue_number: pullNumber, + body, + }); + } + } + + record-on-merge: + if: >- + ( + github.event_name == 'pull_request_target' && + github.event.pull_request.merged == true + ) || + github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + name: ๐Ÿ“ Record CLA after merge + timeout-minutes: 15 + concurrency: + group: cla-signatures-${{ github.repository }} + cancel-in-progress: false + permissions: + contents: write + steps: + - name: ๐Ÿ“ฆ Checkout CLA hub + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: NativeScript/.github + ref: master + path: cla-hub + persist-credentials: false + + - name: ๐Ÿ“œ Checkout org CLA signatures + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: NativeScript/.github + ref: cla-signatures + path: org-cla-signatures + persist-credentials: false + + - name: ๐ŸŸข Setup Node + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: '24' + + - name: ๐Ÿงพ Collect signing comments from recent merged PRs + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + with: + script: | + const path = require('node:path'); + const fs = require('node:fs/promises'); + const { + githubApiErrorStatus, + isRetryableGithubApiError, + withGithubApiRetry, + } = require( + path.join( + process.env.GITHUB_WORKSPACE, + 'cla-hub/scripts/github-api-retry.cjs', + ), + ); + const owner = context.repo.owner; + const repo = context.repo.repo; + + async function collectSigningComments() { + const byMergedDesc = (left, right) => + Date.parse(right.merged_at) - Date.parse(left.merged_at); + const mergedByNumber = new Map(); + for (let page = 1; page <= 50; page += 1) { + const response = await github.rest.pulls.list({ + owner, + repo, + state: 'closed', + sort: 'updated', + direction: 'desc', + per_page: 100, + page, + }); + if (response.data.length === 0) break; + for (const pull of response.data) { + if (pull.merged_at) mergedByNumber.set(pull.number, pull); + } + if (response.data.length < 100) break; + if (mergedByNumber.size >= 50) { + const cutoff = Date.parse( + [...mergedByNumber.values()].sort(byMergedDesc)[49] + .merged_at, + ); + const oldestUpdated = Date.parse( + response.data.at(-1).updated_at, + ); + if (oldestUpdated < cutoff) break; + } + } + const mergedPulls = [...mergedByNumber.values()] + .sort(byMergedDesc) + .slice(0, 50); + + const candidates = new Map( + mergedPulls.map((pull) => [pull.number, pull]), + ); + const eventPull = context.payload.pull_request; + if (eventPull) candidates.set(eventPull.number, eventPull); + + const signingComments = []; + for (const pull of candidates.values()) { + const eligibleLogins = new Set(); + const authorLogin = pull.user?.login; + if (authorLogin) eligibleLogins.add(authorLogin.toLowerCase()); + + const commits = await github.paginate( + github.rest.pulls.listCommits, + { + owner, + repo, + pull_number: pull.number, + per_page: 100, + }, + ); + for (const commit of commits) { + const login = commit.author?.login; + if (login) eligibleLogins.add(login.toLowerCase()); + } + + const comments = await github.paginate( + github.rest.issues.listComments, + { + owner, + repo, + issue_number: pull.number, + per_page: 100, + }, + ); + for (const comment of comments) { + const login = comment.user?.login; + if ( + comment.user?.type !== 'User' || + !login || + !eligibleLogins.has(login.toLowerCase()) + ) { + continue; + } + signingComments.push({ + login, + createdAt: comment.created_at, + body: comment.body ?? '', + }); + } + } + signingComments.sort((left, right) => + left.createdAt.localeCompare(right.createdAt), + ); + return signingComments; + } + + try { + const signingComments = await withGithubApiRetry( + collectSigningComments, + { + maxAttempts: 5, + baseDelayMs: 8_000, + onRetry: ({ attempt, maxAttempts, delayMs, error }) => { + const status = githubApiErrorStatus(error) ?? 'network'; + const detail = + error instanceof Error ? error.message : String(error); + core.info( + `Transient GitHub error (${status}) on CLA collect attempt ${attempt}/${maxAttempts}: ${detail}. Retrying in ${delayMs}ms.`, + ); + }, + }, + ); + await fs.writeFile( + 'cla-signing-comments.json', + `${JSON.stringify(signingComments, null, '\t')}\n`, + ); + } catch (error) { + if (isRetryableGithubApiError(error)) { + const status = githubApiErrorStatus(error) ?? 'network'; + const detail = + error instanceof Error ? error.message : String(error); + core.warning( + `CLA collect failed after retries due to transient GitHub error (${status}): ${detail}. Skipping this run; the next merge rescans the last 50 merges.`, + ); + await fs.writeFile('cla-signing-comments.json', '[]\n'); + return; + } + throw error; + } + + - name: ๐Ÿ“ Prepare target cla-signatures branch and record new signers + id: record + env: + GH_TOKEN: ${{ github.token }} + TARGET_REPO: ${{ github.repository }} + run: | + set -euo pipefail + repo_url="https://x-access-token:${GH_TOKEN}@github.com/${TARGET_REPO}.git" + mkdir -p target-cla-signatures + if git ls-remote --exit-code --heads "$repo_url" cla-signatures >/dev/null 2>&1; then + git clone --depth 1 --branch cla-signatures "$repo_url" target-cla-signatures + else + git -C target-cla-signatures init + git -C target-cla-signatures checkout --orphan cla-signatures + git -C target-cla-signatures remote add origin "$repo_url" + cat > target-cla-signatures/cla-signers.json <<'JSON' + { + "version": 1, + "document": "docs/legal/individual-cla.md", + "allowlist": { + "github": [], + "email": [] + }, + "signers": [] + } + JSON + fi + + record_args=( + --signers target-cla-signatures/cla-signers.json + --record-comments-json cla-signing-comments.json + ) + if [ "${TARGET_REPO}" != "NativeScript/.github" ]; then + record_args+=(--known-signers org-cla-signatures/cla-signers.json) + fi + + node cla-hub/scripts/check-cla.mjs "${record_args[@]}" > cla-record-output.txt + cat cla-record-output.txt + grep -E '^(added|github)=' cla-record-output.txt >> "$GITHUB_OUTPUT" + + - name: ๐ŸŒฑ Commit and push signers + if: steps.record.outputs.added == 'true' + working-directory: target-cla-signatures + env: + CLA_LOGINS: ${{ steps.record.outputs.github }} + run: | + set -euo pipefail + git add cla-signers.json + if git diff --cached --quiet; then + exit 0 + fi + git config user.name 'github-actions[bot]' + git config user.email '41898282+github-actions[bot]@users.noreply.github.com' + git commit -m "Record CLA signers: @${CLA_LOGINS//,/, @}" + git push origin HEAD:refs/heads/cla-signatures diff --git a/.github/workflows/sync-org-cla.yml b/.github/workflows/sync-org-cla.yml new file mode 100644 index 0000000..ab9f1a0 --- /dev/null +++ b/.github/workflows/sync-org-cla.yml @@ -0,0 +1,182 @@ +name: ๐Ÿ”„ Sync Org CLA Signers + +on: + schedule: + - cron: '17 * * * *' + workflow_dispatch: + +permissions: + contents: read + +jobs: + sync: + name: ๐Ÿ”„ Sync CLA signers across NativeScript org + runs-on: ubuntu-latest + timeout-minutes: 15 + concurrency: + group: cla-signatures-NativeScript/.github + cancel-in-progress: false + permissions: + contents: write + steps: + - name: ๐Ÿ“ฆ Checkout CLA hub + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: master + path: cla-hub + persist-credentials: false + + - name: ๐Ÿ“œ Checkout org CLA signatures + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: cla-signatures + path: org-cla-signatures + + - name: ๐ŸŸข Setup Node + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: '24' + + - name: ๐Ÿ”Ž Gather new signers across NativeScript org + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + with: + script: | + const fs = require('node:fs/promises'); + const phrase = 'I have read the CLA and I hereby sign the CLA'; + const orgName = context.repo.owner; + + const signingComments = []; + const importedSigners = []; + + // 1. Search recently merged PRs across the entire NativeScript org that contain the signing phrase + try { + const searchRes = await github.rest.search.issuesAndPullRequests({ + q: `org:${orgName} is:pr is:merged "${phrase}"`, + sort: 'updated', + order: 'desc', + per_page: 50, + }); + + for (const item of searchRes.data.items) { + const parts = item.repository_url.split('/'); + const repo = parts.at(-1); + const owner = parts.at(-2); + + const eligibleLogins = new Set(); + if (item.user?.login) eligibleLogins.add(item.user.login.toLowerCase()); + + const commits = await github.paginate( + github.rest.pulls.listCommits, + { + owner, + repo, + pull_number: item.number, + per_page: 100, + }, + ); + for (const commit of commits) { + if (commit.author?.login) { + eligibleLogins.add(commit.author.login.toLowerCase()); + } + } + + const comments = await github.paginate( + github.rest.issues.listComments, + { + owner, + repo, + issue_number: item.number, + per_page: 100, + }, + ); + for (const comment of comments) { + const login = comment.user?.login; + if ( + comment.user?.type !== 'User' || + !login || + !eligibleLogins.has(login.toLowerCase()) + ) { + continue; + } + signingComments.push({ + login, + createdAt: comment.created_at, + body: comment.body ?? '', + }); + } + } + } catch (err) { + core.warning(`Org PR search encountered error: ${err.message}`); + } + + // 2. Also harvest any repo-local cla-signatures branches on recently pushed public repos + try { + const repos = await github.rest.repos.listForOrg({ + org: orgName, + type: 'public', + sort: 'pushed', + direction: 'desc', + per_page: 40, + }); + for (const r of repos.data) { + if (r.archived || r.fork || r.name === '.github') continue; + try { + const res = await github.rest.repos.getContent({ + owner: orgName, + repo: r.name, + path: 'cla-signers.json', + ref: 'cla-signatures', + }); + if (res.data && 'content' in res.data && res.data.content) { + const parsed = JSON.parse( + Buffer.from(res.data.content, 'base64').toString('utf8'), + ); + if (Array.isArray(parsed.signers)) { + importedSigners.push(...parsed.signers); + } + } + } catch (err) { + if (err.status !== 404) { + core.info(`Skipped ${r.name} cla-signatures: ${err.message}`); + } + } + } + } catch (err) { + core.warning(`Repo cla-signatures scan encountered error: ${err.message}`); + } + + signingComments.sort((a, b) => a.createdAt.localeCompare(b.createdAt)); + await fs.writeFile( + 'org-signing-comments.json', + `${JSON.stringify(signingComments, null, '\t')}\n`, + ); + await fs.writeFile( + 'org-imported-signers.json', + `${JSON.stringify(importedSigners, null, '\t')}\n`, + ); + + - name: ๐Ÿ“ Apply new signers to org cla-signers.json + id: record + run: | + node cla-hub/scripts/check-cla.mjs \ + --signers org-cla-signatures/cla-signers.json \ + --record-comments-json org-signing-comments.json \ + --import-signers-json org-imported-signers.json > cla-sync-output.txt + cat cla-sync-output.txt + grep -E '^(added|github)=' cla-sync-output.txt >> "$GITHUB_OUTPUT" + + - name: ๐ŸŒฑ Commit and push org signers + if: steps.record.outputs.added == 'true' + working-directory: org-cla-signatures + env: + CLA_LOGINS: ${{ steps.record.outputs.github }} + run: | + set -euo pipefail + git add cla-signers.json + if git diff --cached --quiet; then + exit 0 + fi + git config user.name 'github-actions[bot]' + git config user.email '41898282+github-actions[bot]@users.noreply.github.com' + git commit -m "Record CLA signers: @${CLA_LOGINS//,/, @}" + git push origin HEAD:refs/heads/cla-signatures diff --git a/.github/workflows/test-cla.yml b/.github/workflows/test-cla.yml new file mode 100644 index 0000000..e7f5a41 --- /dev/null +++ b/.github/workflows/test-cla.yml @@ -0,0 +1,38 @@ +name: ๐Ÿงช Test CLA Scripts + +on: + push: + branches: + - master + pull_request: + +permissions: + contents: read + +jobs: + test: + name: ๐Ÿงช Unit tests (check-cla) + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: ๐Ÿ“ฆ Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: ๐Ÿ“œ Checkout org CLA signatures + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: cla-signatures + path: org-cla-signatures + persist-credentials: false + + - name: ๐ŸŸข Setup Node + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: '24' + + - name: ๐Ÿงช Run CLA unit tests and validate org-cla-signatures + run: | + node --test scripts/check-cla.test.mjs + node -e 'import("./scripts/check-cla.mjs").then(async m => { const fs = await import("node:fs/promises"); const f = m.parseClaSignersFile(await fs.readFile("org-cla-signatures/cla-signers.json", "utf8")); console.log("Validated cla-signers.json โ€” allowlisted:", f.allowlist.github.length, "signers:", f.signers.length); })' diff --git a/CLA.md b/CLA.md new file mode 100644 index 0000000..15aeee3 --- /dev/null +++ b/CLA.md @@ -0,0 +1,71 @@ +# NativeScript Contributor License Agreement (CLA) + +All external pull requests across the [`NativeScript`](https://github.com/NativeScript) GitHub organization require a signed Contributor License Agreement before merging. Contributors retain copyright in their work while granting the license described in the agreement. + +- **Individuals:** [Individual Contributor License Agreement (ICLA v2.0)](./docs/legal/individual-cla.md) +- **Organizations / Employers:** [Corporate Contributor License Agreement (CCLA)](./docs/legal/corporate-cla.md) + +--- + +## How to Sign (Individual) + +1. Open your pull request in any `NativeScript` repository. +2. Read the [Individual CLA](./docs/legal/individual-cla.md). +3. Post a comment on the pull request with the exact text: + + ```text + I have read the CLA and I hereby sign the CLA + ``` + +4. That comment immediately satisfies the `โœ๏ธ CLA` status check on your pull request (only when posted by the pull request author or commit author). A bystander comment cannot sign on behalf of another contributor. + +### Sign Once for the Entire `NativeScript` Organization + +- **Signing once covers past, present, and future contributions** from your GitHub account across **every repository** in `github.com/NativeScript`. +- Previous signers of the OpenJS Foundation NativeScript CLA have already been migrated into [`cla-signers.json`](https://github.com/NativeScript/.github/blob/cla-signatures/cla-signers.json) on the `cla-signatures` branch and will pass automatically. +- After your pull request merges, our workflow automatically records your GitHub username on the [`cla-signatures`](https://github.com/NativeScript/.github/blob/cla-signatures/cla-signers.json) branch so future pull requests pass silently with zero extra steps. +- Because signer records are read from the protected `cla-signatures` branch (never from the pull request branch), editing `cla-signers.json` inside a pull request does not pass the check. + +--- + +## How to Sign (Corporate / Entity) + +If an employer or legal entity owns the contribution and requires a corporate agreement rather than individual sign-off under Section 4 of the ICLA, follow the steps in the [Corporate CLA guide](./docs/legal/corporate-cla.md) via [operations@openjsf.org](mailto:operations@openjsf.org). + +--- + +## Troubleshooting + +### Commit author is not linked to a GitHub account + +If a commit in your pull request was authored with a local `git config user.email` address that is not registered on your GitHub account, GitHub cannot associate that commit with your GitHub username. To resolve it: + +1. Add the commit email address to your GitHub account at [github.com/settings/emails](https://github.com/settings/emails), **or** amend the commit author (`git commit --amend --reset-author`) using your GitHub-verified email and force-push your branch. +2. Comment `I have read the CLA and I hereby sign the CLA` if you have not yet signed. + +--- + +## Who Does Not Need to Sign + +The following accounts are allowlisted in [`cla-signers.json`](https://github.com/NativeScript/.github/blob/cla-signatures/cla-signers.json) and pass automatically: + +- Active `NativeScript` organization maintainers and service accounts listed in `allowlist.github` +- Automated GitHub accounts ending in `[bot]` or prefixed with `app/` (e.g., `dependabot[bot]`, `github-actions[bot]`) + +--- + +## Maintainer Reference + +- **Do not merge** a pull request while the `โœ๏ธ CLA` check is failing. +- Individual signatures are recorded automatically on `cla-signatures` when a pull request merges and synced org-wide to `NativeScript/.github@cla-signatures` (you can also trigger the `Sync Org CLA Signers` workflow manually via `workflow_dispatch`). +- **Recording a Corporate CLA:** Add authorized GitHub usernames to `cla-signers.json` on the `cla-signatures` branch of `NativeScript/.github` with `"signedAt": "YYYY-MM-DD"` and `"cla": "corporate"`. +- **Carrying commits from a superseded PR:** If a contributor signed on an earlier closed pull request and a maintainer carries their commits into a new pull request, record their original signing comment onto `NativeScript/.github@cla-signatures`: + + ```sh + git fetch origin cla-signatures:refs/remotes/origin/cla-signatures + git worktree add --detach ../cla-signatures origin/cla-signatures + node scripts/check-cla.mjs --signers ../cla-signatures/cla-signers.json --record-signer --signed-at --comment-file + git -C ../cla-signatures commit -am "chore(cla): record @ from #" + git -C ../cla-signatures push origin HEAD:cla-signatures + git worktree remove ../cla-signatures + ``` diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 87136f3..8f6e35d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -32,7 +32,7 @@ Here are some guides on how to do that: Before you begin: -- Read and sign the [NativeScript Contribution License Agreement](http://www.nativescript.org/cla). +- Read the [NativeScript Contributor License Agreement (CLA)](https://github.com/NativeScript/.github/blob/master/CLA.md). If you haven't signed before, our `โœ๏ธ CLA` bot will prompt you on your pull request to sign by commenting `I have read the CLA and I hereby sign the CLA`. - Make sure there is an issue for the bug or feature you will be working on. Following these steps is the best way to get you code included in the project: @@ -67,7 +67,7 @@ git checkout -b main 2. Before you submit your PR: - Rebase your changes to the latest main: `git pull --rebase upstream main`. - - Ensure all unit test are green for Android and iOS. Check [running unit tests](DevelopmentWorkflow.md#running-unit-tests). + - Ensure all unit tests are green. Check [running unit tests](https://github.com/NativeScript/NativeScript/blob/main/tools/notes/DevelopmentWorkflow.md#unit-testing). 3. Push your fork. If you have rebased you might have to use force-push your branch: diff --git a/docs/legal/corporate-cla.md b/docs/legal/corporate-cla.md new file mode 100644 index 0000000..d6a3c4b --- /dev/null +++ b/docs/legal/corporate-cla.md @@ -0,0 +1,20 @@ +# NativeScript Corporate Contributor License Agreement (CCLA) + +- **Project Name:** NativeScript (OpenJS Foundation) +- **Project Entity:** NativeScript (OpenJS Foundation) +- **Contact:** [operations@openjsf.org](mailto:operations@openjsf.org) + +This Corporate Contributor License Agreement path is for legal entities or employers that own intellectual property being contributed to NativeScript. Individuals contributing work they own personally (or with employer waiver/permission under Section 4 of the ICLA) should sign the [Individual Contributor License Agreement](./individual-cla.md) directly on their pull request instead. + +## How to Execute a Corporate CLA + +1. Have an authorized representative of your organization contact [operations@openjsf.org](mailto:operations@openjsf.org) referencing: + - **Project Name:** `NativeScript (OpenJS Foundation)` + - **Project Entity:** `NativeScript (OpenJS Foundation)` + - Organization legal name and address + - Authorized representative name, title, and contact email + - GitHub usernames authorized to contribute on behalf of the organization +2. Once the Corporate CLA is accepted by the OpenJS Foundation / NativeScript Technical Steering Committee (TSC), a maintainer records the authorized GitHub usernames in [`cla-signers.json`](https://github.com/NativeScript/.github/blob/cla-signatures/cla-signers.json) on the `cla-signatures` branch with `"cla": "corporate"`. +3. Comment on your open pull request letting maintainers know once your Corporate CLA has been submitted so the `โœ๏ธ CLA` check can be re-run. + +See the [NativeScript CLA Guide](../../CLA.md) for full details. diff --git a/docs/legal/individual-cla.md b/docs/legal/individual-cla.md new file mode 100644 index 0000000..ebde5ed --- /dev/null +++ b/docs/legal/individual-cla.md @@ -0,0 +1,55 @@ +# NativeScript Individual Contributor License Agreement (ICLA) v2.0 + +- **Project Name:** NativeScript (OpenJS Foundation) +- **Project Entity:** NativeScript (OpenJS Foundation) +- **PDF Version:** [OpenJS Foundation Individual CLA v2.0 (PDF)](https://images.prismic.io/openjsf/4c740999-4bd7-4f69-8c4a-b80db0919690_OpenJS-Foundation-ICLA-2020-09-23.pdf) + +Thank you for your interest in the project specified above (the "Project"). In order to clarify the intellectual property license granted with Contributions from any person or entity, the Project must have a Contributor License Agreement (CLA) on file that has been signed by each Contributor, indicating agreement to the license terms below. This license is for your protection as a Contributor as well as the protection of the Project and its users; it does not change your rights to use your own Contributions for any other purpose. + +You accept and agree to the following terms and conditions for Your present and future Contributions submitted to the Project across the `NativeScript` GitHub organization by commenting `I have read the CLA and I hereby sign the CLA` on a Project pull request from your GitHub account, or by emailing a signed copy of the [PDF agreement](https://images.prismic.io/openjsf/4c740999-4bd7-4f69-8c4a-b80db0919690_OpenJS-Foundation-ICLA-2020-09-23.pdf) to [operations@openjsf.org](mailto:operations@openjsf.org). Please read this document carefully before signing and keep a copy for your records. + +> Organizations that own the contributed work should execute the [Corporate Contributor License Agreement](./corporate-cla.md) instead. + +--- + +You accept and agree to the following terms and conditions for Your present and future Contributions submitted to the Project. In return, the Project shall not use Your Contributions in a way that is contrary to the public benefit or inconsistent with its charter at the time of the Contribution. Except for the license granted herein to the Project and recipients of software distributed by the Project, You reserve all right, title, and interest in and to Your Contributions. + +## 1. Definitions + +"You" (or "Your") shall mean the copyright owner or legal entity authorized by the copyright owner that is making this Agreement with the Project. For legal entities, the entity making a Contribution and all other entities that control, are controlled by, or are under common control with that entity are considered to be a single Contributor. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"Contribution" shall mean the code, documentation or other original works of authorship, including any modifications or additions to an existing work, that is intentionally submitted by You to the Project for inclusion in, or documentation of, any of the products owned or managed by the Project (the "Work"). For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Project or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by You as "Not a Contribution." + +## 2. Grant of Copyright License + +Subject to the terms and conditions of this Agreement, You hereby grant to the Project and to recipients of software distributed by the Project a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, and distribute Your Contributions and such derivative works. + +## 3. Grant of Patent License + +Subject to the terms and conditions of this Agreement, You hereby grant to the Project and to recipients of software distributed by the Project a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by You that are necessarily infringed by Your Contribution(s) alone or by combination of Your Contribution(s) with the Work to which such Contribution(s) were submitted. If any entity institutes patent litigation against You or any other entity (including a cross-claim or counterclaim in a lawsuit) alleging that your Contribution, or the Work to which you have contributed, constitutes direct or contributory patent infringement, then any patent licenses granted to that entity under this Agreement for that Contribution or Work shall terminate as of the date such litigation is filed. + +## 4. Employer Rights and Authority + +You represent that you are legally entitled to grant the above license. If your employer(s) has rights to intellectual property that you create that includes your Contributions, you represent that you have received permission to make Contributions on behalf of that employer, that your employer has waived such rights for your Contributions to the Project, or that your employer has executed a separate [Corporate CLA](./corporate-cla.md) with the Project. + +## 5. Original Creation + +You represent that each of Your Contributions is Your original creation (see section 7 for submissions on behalf of others). You represent that Your Contribution submissions include complete details of any third-party license or other restriction (including, but not limited to, related patents and trademarks) of which you are personally aware and which are associated with any part of Your Contributions. + +## 6. Disclaimer of Warranty + +You are not expected to provide support for Your Contributions, except to the extent You desire to provide support. You may provide support for free, for a fee, or not at all. Unless required by applicable law or agreed to in writing, You provide Your Contributions on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. + +## 7. Third-Party Submissions + +Should You wish to submit work that is not Your original creation, You may submit it to the Project separately from any Contribution, identifying the complete details of its source and of any license or other restriction (including, but not limited to, related patents, trademarks, and license agreements) of which you are personally aware, and conspicuously marking the work as "Submitted on behalf of a third-party: [named here]". + +## 8. Notice of Changes + +You agree to notify the Project of any facts or circumstances of which you become aware that would make these representations inaccurate in any respect. + +--- + +## How to Sign + +See the [NativeScript CLA Guide](../../CLA.md). diff --git a/scripts/check-cla.mjs b/scripts/check-cla.mjs new file mode 100644 index 0000000..2e20e03 --- /dev/null +++ b/scripts/check-cla.mjs @@ -0,0 +1,507 @@ +import { readFile, writeFile } from 'node:fs/promises'; +import { pathToFileURL } from 'node:url'; +import { resolve } from 'node:path'; + +export const individualClaSigningPhrase = + 'I have read the CLA and I hereby sign the CLA'; + +const githubBotLoginPattern = /\[bot\]$/i; + +export function normalize(value) { + return String(value).trim().toLowerCase(); +} + +function identityLabel(identity) { + if (identity.githubLogin) { + return `@${identity.githubLogin}`; + } + if (identity.name && identity.email) { + return `${identity.name} <${identity.email}>`; + } + if (identity.email) { + return identity.email; + } + if (identity.name) { + return identity.name; + } + return 'unknown identity'; +} + +export function parseClaSignersFile(raw) { + const parsed = JSON.parse(raw); + if ( + typeof parsed !== 'object' || + parsed === null || + !('version' in parsed) || + parsed.version !== 1 + ) { + throw new Error('CLA signers file must be version 1 JSON'); + } + + if ( + typeof parsed.document !== 'string' || + typeof parsed.allowlist !== 'object' || + parsed.allowlist === null || + !Array.isArray(parsed.allowlist.github) || + !Array.isArray(parsed.allowlist.email) || + !Array.isArray(parsed.signers) + ) { + throw new Error('CLA signers file is missing allowlist or signers'); + } + + return parsed; +} + +export function serializeClaSignersFile(file) { + return `${JSON.stringify(file, null, '\t')}\n`; +} + +export function mergeClaSignersFiles(primary, extra) { + if (!extra) return primary; + + const seenGithubAllow = new Set(primary.allowlist.github.map(normalize)); + const allowGithub = [...primary.allowlist.github]; + for (const login of extra.allowlist.github) { + const key = normalize(login); + if (key && !seenGithubAllow.has(key)) { + seenGithubAllow.add(key); + allowGithub.push(login); + } + } + + const seenEmailAllow = new Set(primary.allowlist.email.map(normalize)); + const allowEmail = [...primary.allowlist.email]; + for (const email of extra.allowlist.email) { + const key = normalize(email); + if (key && !seenEmailAllow.has(key)) { + seenEmailAllow.add(key); + allowEmail.push(email); + } + } + + const seenSigners = new Set(primary.signers.map((s) => normalize(s.github))); + const signers = [...primary.signers]; + for (const signer of extra.signers) { + const key = normalize(signer.github); + if (key && !seenSigners.has(key)) { + seenSigners.add(key); + signers.push(signer); + } + } + + return { + ...primary, + allowlist: { + github: allowGithub, + email: allowEmail, + }, + signers, + }; +} + +export function isIndividualClaSigningComment(body) { + return typeof body === 'string' && body.trim() === individualClaSigningPhrase; +} + +export function applyIndividualClaSigningComment(input) { + if (!isIndividualClaSigningComment(input.comment)) { + return { + file: input.file, + status: 'ignored', + reason: 'not_signing_comment', + }; + } + + const login = String(input.github ?? '').trim(); + if (!login) { + return { file: input.file, status: 'ignored', reason: 'missing_login' }; + } + + const normalizedLogin = normalize(login); + if ( + input.file.signers.some((signer) => normalize(signer.github) === normalizedLogin) || + input.file.allowlist.github.some((entry) => normalize(entry) === normalizedLogin) || + (input.knownSignersFile && + (input.knownSignersFile.signers.some( + (signer) => normalize(signer.github) === normalizedLogin, + ) || + input.knownSignersFile.allowlist.github.some( + (entry) => normalize(entry) === normalizedLogin, + ))) + ) { + return { file: input.file, status: 'already_signed', github: login }; + } + + return { + file: { + ...input.file, + signers: [ + ...input.file.signers, + { + github: login, + signedAt: input.signedAt, + cla: 'individual', + }, + ], + }, + status: 'recorded', + github: login, + }; +} + +export function applyIndividualClaSigningComments( + file, + comments, + knownSignersFile = null, +) { + let updated = file; + const recorded = []; + const recordedLogins = new Set(); + + for (const comment of comments) { + const signedAt = + typeof comment.createdAt === 'string' && comment.createdAt.length >= 10 + ? comment.createdAt.slice(0, 10) + : new Date().toISOString().slice(0, 10); + const result = applyIndividualClaSigningComment({ + file: updated, + knownSignersFile, + github: comment.login, + signedAt, + comment: comment.body, + }); + updated = result.file; + if (result.status !== 'recorded') { + continue; + } + + const login = normalize(result.github); + if (recordedLogins.has(login)) { + continue; + } + recordedLogins.add(login); + recorded.push(result.github); + } + + return { file: updated, recorded }; +} + +export function isAllowlistedIdentity(identity, signersFile) { + const login = identity.githubLogin ? normalize(identity.githubLogin) : null; + if ( + login && + (githubBotLoginPattern.test(login) || login.startsWith('app/')) + ) { + return true; + } + if ( + login && + signersFile.allowlist.github.some((entry) => normalize(entry) === login) + ) { + return true; + } + + const email = identity.email ? normalize(identity.email) : null; + return Boolean( + email && + signersFile.allowlist.email.some((entry) => normalize(entry) === email), + ); +} + +export function hasSignedCla(identity, signersFile) { + const login = identity.githubLogin ? normalize(identity.githubLogin) : null; + if (!login) { + return false; + } + + return signersFile.signers.some( + (signer) => normalize(signer.github) === login, + ); +} + +export function checkClaIdentities(identities, signersFile) { + const missing = []; + const seen = new Set(); + + for (const identity of identities) { + const key = [identity.githubLogin, identity.email, identity.name] + .map((part) => (part ? normalize(part) : '')) + .join('|'); + if (seen.has(key)) { + continue; + } + seen.add(key); + + if (isAllowlistedIdentity(identity, signersFile)) { + continue; + } + if (hasSignedCla(identity, signersFile)) { + continue; + } + + const reason = identity.githubLogin + ? `${identityLabel(identity)} has not signed the CLA` + : `Commit author \`${identityLabel(identity)}\` is not linked to a GitHub account (add this email at https://github.com/settings/emails or amend the commit author, then sign the CLA)`; + missing.push({ identity, reason }); + } + + return missing.length === 0 ? { ok: true } : { ok: false, missing }; +} + +export function formatClaFailure(result) { + const lines = [ + 'Unsigned contributions cannot merge.', + 'Read https://github.com/NativeScript/.github/blob/master/docs/legal/individual-cla.md (or corporate-cla.md if an organization owns the work).', + `Comment on the pull request: ${individualClaSigningPhrase}`, + 'That signing comment satisfies this check across all NativeScript repositories.', + 'The signer is recorded on the cla-signatures branch after the pull request merges.', + '', + 'Missing CLA status:', + ...result.missing.map((entry) => `- ${entry.reason}`), + ]; + return lines.join('\n'); +} + +export function shouldRunClaCheckJob(input) { + return input.eventName === 'pull_request_target' && input.action !== 'closed'; +} + +export function pickClaRerunCandidate(runs) { + for (const run of runs) { + if (run.status !== 'completed') { + return run; + } + if (run.conclusion !== 'skipped') { + return run; + } + } + return null; +} + +function readFlag(args, flag) { + const index = args.indexOf(flag); + if (index === -1) { + return null; + } + const value = args[index + 1]; + if (!value || value.startsWith('--')) { + return null; + } + return value; +} + +async function runRecordSingleCli(args) { + const signersPath = readFlag(args, '--signers'); + const github = readFlag(args, '--record-signer'); + const signedAt = readFlag(args, '--signed-at'); + const commentPath = readFlag(args, '--comment-file'); + + if (!signersPath || !github || !signedAt || !commentPath) { + throw new Error( + 'Usage: node scripts/check-cla.mjs --signers --record-signer --signed-at --comment-file ', + ); + } + + const current = parseClaSignersFile(await readFile(signersPath, 'utf8')); + const recorded = applyIndividualClaSigningComment({ + file: current, + github, + signedAt, + comment: await readFile(commentPath, 'utf8'), + }); + + switch (recorded.status) { + case 'ignored': + console.log('skipped=true'); + console.log('added=false'); + break; + case 'already_signed': + console.log('skipped=false'); + console.log('added=false'); + console.log(`github=${recorded.github}`); + break; + case 'recorded': + await writeFile( + signersPath, + serializeClaSignersFile(recorded.file), + 'utf8', + ); + console.log('skipped=false'); + console.log('added=true'); + console.log(`github=${recorded.github}`); + break; + default: + throw new Error(`Unhandled CLA record status: ${JSON.stringify(recorded)}`); + } +} + +async function runRecordCommentsCli(args) { + const signersPath = readFlag(args, '--signers'); + const knownSignersPath = readFlag(args, '--known-signers'); + const commentsPath = readFlag(args, '--record-comments-json'); + const importSignersPath = readFlag(args, '--import-signers-json'); + + if (!signersPath || (!commentsPath && !importSignersPath)) { + throw new Error( + 'Usage: node scripts/check-cla.mjs --signers [--known-signers ] --record-comments-json [--import-signers-json ]', + ); + } + + let current = parseClaSignersFile(await readFile(signersPath, 'utf8')); + const known = knownSignersPath + ? parseClaSignersFile(await readFile(knownSignersPath, 'utf8')) + : null; + + const recorded = []; + const recordedLogins = new Set(); + + if (commentsPath) { + const commentsRaw = JSON.parse(await readFile(commentsPath, 'utf8')); + if (!Array.isArray(commentsRaw)) { + throw new Error('CLA signing comments JSON must be an array'); + } + const commentRes = applyIndividualClaSigningComments( + current, + commentsRaw, + known, + ); + current = commentRes.file; + for (const login of commentRes.recorded) { + const norm = normalize(login); + if (!recordedLogins.has(norm)) { + recordedLogins.add(norm); + recorded.push(login); + } + } + } + + if (importSignersPath) { + const importedRaw = JSON.parse(await readFile(importSignersPath, 'utf8')); + if (!Array.isArray(importedRaw)) { + throw new Error('Imported signers JSON must be an array'); + } + for (const entry of importedRaw) { + if (!entry || typeof entry.github !== 'string' || !entry.github.trim()) { + continue; + } + const norm = normalize(entry.github); + const existsInCurrent = + current.signers.some((s) => normalize(s.github) === norm) || + current.allowlist.github.some((a) => normalize(a) === norm); + const existsInKnown = + known && + (known.signers.some((s) => normalize(s.github) === norm) || + known.allowlist.github.some((a) => normalize(a) === norm)); + if (existsInCurrent || existsInKnown) { + continue; + } + current = { + ...current, + signers: [ + ...current.signers, + { + github: entry.github.trim(), + signedAt: + typeof entry.signedAt === 'string' && entry.signedAt.trim() + ? entry.signedAt.trim() + : new Date().toISOString().slice(0, 10), + cla: entry.cla === 'corporate' || entry.cla === 'entity' ? entry.cla : 'individual', + }, + ], + }; + if (!recordedLogins.has(norm)) { + recordedLogins.add(norm); + recorded.push(entry.github.trim()); + } + } + } + + if (recorded.length > 0) { + await writeFile(signersPath, serializeClaSignersFile(current), 'utf8'); + } + + console.log(`added=${recorded.length > 0}`); + console.log(`github=${recorded.join(',')}`); +} + +async function runCheckCli(args) { + const signersPath = readFlag(args, '--signers'); + const extraSignersPath = readFlag(args, '--extra-signers'); + const identitiesPath = readFlag(args, '--identities-json'); + const signingCommentsPath = readFlag(args, '--signing-comments-json'); + const missingJsonPath = readFlag(args, '--missing-json'); + + if ( + !signersPath || + !identitiesPath || + (args.includes('--signing-comments-json') && !signingCommentsPath) + ) { + throw new Error( + 'Usage: node scripts/check-cla.mjs --signers [--extra-signers ] --identities-json [--signing-comments-json ] [--missing-json ]', + ); + } + + let signersFile = parseClaSignersFile(await readFile(signersPath, 'utf8')); + if (extraSignersPath) { + const extraFile = parseClaSignersFile( + await readFile(extraSignersPath, 'utf8'), + ); + signersFile = mergeClaSignersFiles(signersFile, extraFile); + } + + if (signingCommentsPath) { + const commentsRaw = JSON.parse(await readFile(signingCommentsPath, 'utf8')); + if (!Array.isArray(commentsRaw)) { + throw new Error('CLA signing comments JSON must be an array'); + } + signersFile = applyIndividualClaSigningComments( + signersFile, + commentsRaw, + ).file; + } + + const identitiesRaw = JSON.parse(await readFile(identitiesPath, 'utf8')); + if (!Array.isArray(identitiesRaw)) { + throw new Error('Identities JSON must be an array'); + } + + const result = checkClaIdentities(identitiesRaw, signersFile); + if (!result.ok) { + if (missingJsonPath) { + await writeFile( + missingJsonPath, + `${JSON.stringify(result.missing, null, '\t')}\n`, + 'utf8', + ); + } + console.error(formatClaFailure(result)); + process.exitCode = 1; + } else if (missingJsonPath) { + await writeFile(missingJsonPath, '[]\n', 'utf8'); + } +} + +export async function runCli(args) { + if ( + args.includes('--record-comments-json') || + args.includes('--import-signers-json') + ) { + await runRecordCommentsCli(args); + return; + } + + if (args.includes('--record-signer')) { + await runRecordSingleCli(args); + return; + } + + await runCheckCli(args); +} + +const isDirectRun = + process.argv[1] && + import.meta.url === pathToFileURL(resolve(process.argv[1])).href; + +if (isDirectRun) { + await runCli(process.argv.slice(2)); +} diff --git a/scripts/check-cla.test.mjs b/scripts/check-cla.test.mjs new file mode 100644 index 0000000..384325d --- /dev/null +++ b/scripts/check-cla.test.mjs @@ -0,0 +1,262 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { createRequire } from 'node:module'; + +import { + applyIndividualClaSigningComment, + applyIndividualClaSigningComments, + checkClaIdentities, + individualClaSigningPhrase, + isIndividualClaSigningComment, + mergeClaSignersFiles, + parseClaSignersFile, + pickClaRerunCandidate, + runCli, + serializeClaSignersFile, + shouldRunClaCheckJob, +} from './check-cla.mjs'; + +const require = createRequire(import.meta.url); +const { + isRetryableGithubApiError, + withGithubApiRetry, +} = require('./github-api-retry.cjs'); + +function makeBaseSigners() { + return { + version: 1, + document: 'docs/legal/individual-cla.md', + allowlist: { + github: ['NathanWalker', 'nativescript-oss'], + email: ['noreply@anthropic.com'], + }, + signers: [ + { + github: 'ExistingContributor', + signedAt: '2026-01-15', + cla: 'individual', + }, + ], + }; +} + +test('matches exact signing comment with optional surrounding whitespace only', () => { + assert.equal(isIndividualClaSigningComment(individualClaSigningPhrase), true); + assert.equal( + isIndividualClaSigningComment(` \n${individualClaSigningPhrase}\n `), + true, + ); + assert.equal( + isIndividualClaSigningComment('I hereby sign the CLA'), + false, + ); + assert.equal( + isIndividualClaSigningComment(`${individualClaSigningPhrase}.`), + false, + ); +}); + +test('allows bots, app/*, allowlisted logins/emails, and existing signers case-insensitively', () => { + const file = makeBaseSigners(); + const res = checkClaIdentities( + [ + { githubLogin: 'nathanwalker', name: 'Nathan', email: null }, + { githubLogin: 'dependabot[bot]', name: 'dependabot', email: null }, + { githubLogin: 'app/dependabot', name: 'dependabot', email: null }, + { githubLogin: null, name: 'Claude', email: 'NOREPLY@anthropic.com' }, + { githubLogin: 'existingcontributor', name: 'EC', email: null }, + ], + file, + ); + assert.deepEqual(res, { ok: true }); +}); + +test('fails unsigned contributors and bystander comments do not sign for PR author', () => { + const base = makeBaseSigners(); + const withBystander = applyIndividualClaSigningComments(base, [ + { + login: 'RandomBystander', + createdAt: '2026-11-22T18:00:00Z', + body: individualClaSigningPhrase, + }, + ]).file; + + const res = checkClaIdentities( + [{ githubLogin: 'NewContributor', name: 'New', email: 'new@example.com' }], + withBystander, + ); + assert.equal(res.ok, false); + assert.equal(res.missing.length, 1); + assert.match(res.missing[0].reason, /@NewContributor has not signed the CLA/); +}); + +test('passes when unsigned contributor posts exact signing comment', () => { + const base = makeBaseSigners(); + const afterSign = applyIndividualClaSigningComments(base, [ + { + login: 'NewContributor', + createdAt: '2026-11-22T18:50:35Z', + body: individualClaSigningPhrase, + }, + ]); + assert.deepEqual(afterSign.recorded, ['NewContributor']); + const res = checkClaIdentities( + [{ githubLogin: 'newcontributor', name: 'New', email: null }], + afterSign.file, + ); + assert.deepEqual(res, { ok: true }); +}); + +test('provides actionable diagnostics when commit has no linked GitHub login', () => { + const base = makeBaseSigners(); + const res = checkClaIdentities( + [{ githubLogin: null, name: 'Local Dev', email: 'dev@local.invalid' }], + base, + ); + assert.equal(res.ok, false); + assert.match( + res.missing[0].reason, + /Local Dev .*https:\/\/github\.com\/settings\/emails/, + ); +}); + +test('merges org and repo-local signers without duplicates and skips known signers on record', () => { + const org = makeBaseSigners(); + const local = { + version: 1, + document: 'docs/legal/individual-cla.md', + allowlist: { github: ['nathanwalker', 'ExtraMaintainer'], email: [] }, + signers: [ + { github: 'existingcontributor', signedAt: '2026-02-01', cla: 'individual' }, + { github: 'RepoLocalSigner', signedAt: '2026-11-22', cla: 'individual' }, + ], + }; + + const merged = mergeClaSignersFiles(org, local); + assert.equal(merged.allowlist.github.length, 3); + assert.equal(merged.signers.length, 2); + assert.deepEqual( + checkClaIdentities( + [{ githubLogin: 'repolocalsigner', name: null, email: null }], + merged, + ), + { ok: true }, + ); + + // Recording someone already in org signers against an empty repo-local file skips adding + const emptyLocal = { + version: 1, + document: 'docs/legal/individual-cla.md', + allowlist: { github: [], email: [] }, + signers: [], + }; + const skipRes = applyIndividualClaSigningComment({ + file: emptyLocal, + knownSignersFile: org, + github: 'ExistingContributor', + signedAt: '2026-11-22', + comment: individualClaSigningPhrase, + }); + assert.equal(skipRes.status, 'already_signed'); + assert.equal(skipRes.file.signers.length, 0); +}); + +test('CLI check and record modes write expected files and exit codes', async () => { + const dir = await mkdtemp(join(tmpdir(), 'ns-cla-test-')); + try { + const signersPath = join(dir, 'cla-signers.json'); + const identitiesPath = join(dir, 'identities.json'); + const commentsPath = join(dir, 'comments.json'); + const missingPath = join(dir, 'missing.json'); + + await writeFile(signersPath, serializeClaSignersFile(makeBaseSigners()), 'utf8'); + await writeFile( + identitiesPath, + JSON.stringify([{ githubLogin: 'AliceDev', name: 'Alice', email: null }]), + 'utf8', + ); + await writeFile(commentsPath, '[]', 'utf8'); + + const prevCode = process.exitCode; + process.exitCode = 0; + await runCli([ + '--signers', + signersPath, + '--identities-json', + identitiesPath, + '--signing-comments-json', + commentsPath, + '--missing-json', + missingPath, + ]); + assert.equal(process.exitCode, 1); + process.exitCode = prevCode; + + const missing = JSON.parse(await readFile(missingPath, 'utf8')); + assert.equal(missing.length, 1); + + // Now sign via comment and record + await writeFile( + commentsPath, + JSON.stringify([ + { + login: 'AliceDev', + createdAt: '2026-11-22T19:00:00Z', + body: individualClaSigningPhrase, + }, + ]), + 'utf8', + ); + await runCli([ + '--signers', + signersPath, + '--record-comments-json', + commentsPath, + ]); + const updated = parseClaSignersFile(await readFile(signersPath, 'utf8')); + assert.equal( + updated.signers.some((s) => s.github === 'AliceDev'), + true, + ); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test('workflow event helpers and retry helper behave deterministically', async () => { + assert.equal( + shouldRunClaCheckJob({ eventName: 'pull_request_target', action: 'opened' }), + true, + ); + assert.equal( + shouldRunClaCheckJob({ eventName: 'pull_request_target', action: 'closed' }), + false, + ); + assert.deepEqual( + pickClaRerunCandidate([ + { id: 1, event: 'pull_request_target', status: 'completed', conclusion: 'skipped' }, + { id: 2, event: 'pull_request_target', status: 'completed', conclusion: 'failure' }, + ]), + { id: 2, event: 'pull_request_target', status: 'completed', conclusion: 'failure' }, + ); + + let attempts = 0; + const value = await withGithubApiRetry( + async () => { + attempts += 1; + if (attempts < 3) { + const err = new Error('Bad Gateway'); + err.status = 502; + throw err; + } + return 'ok'; + }, + { maxAttempts: 4, baseDelayMs: 1 }, + ); + assert.equal(value, 'ok'); + assert.equal(attempts, 3); + assert.equal(isRetryableGithubApiError({ status: 404 }), false); +}); diff --git a/scripts/github-api-retry.cjs b/scripts/github-api-retry.cjs new file mode 100644 index 0000000..fc02721 --- /dev/null +++ b/scripts/github-api-retry.cjs @@ -0,0 +1,86 @@ +'use strict'; + +/** + * Bounded retries for transient GitHub API 5xx / network errors in github-script steps. + * Kept as CommonJS so `actions/github-script` can `require()` it directly. + */ + +const defaultMaxAttempts = 4; +const defaultBaseDelayMs = 1_000; + +function isRetryableGithubApiStatus(status) { + return Number.isInteger(status) && status >= 500 && status < 600; +} + +function githubApiErrorStatus(error) { + if (error == null || typeof error !== 'object') return undefined; + if (typeof error.status === 'number') return error.status; + const response = error.response; + if (response != null && typeof response === 'object' && typeof response.status === 'number') { + return response.status; + } + return undefined; +} + +function isRetryableGithubNetworkError(error) { + if (error == null || typeof error !== 'object') return false; + const code = 'code' in error ? error.code : undefined; + if ( + code === 'ECONNRESET' || + code === 'ETIMEDOUT' || + code === 'ECONNREFUSED' || + code === 'ENOTFOUND' || + code === 'EAI_AGAIN' + ) { + return true; + } + const message = + error instanceof Error + ? error.message + : typeof error.message === 'string' + ? error.message + : ''; + return /ECONNRESET|ETIMEDOUT|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|socket hang up|fetch failed|upstream connect error/i.test( + message, + ); +} + +function isRetryableGithubApiError(error) { + const status = githubApiErrorStatus(error); + if (status !== undefined) return isRetryableGithubApiStatus(status); + return isRetryableGithubNetworkError(error); +} + +async function withGithubApiRetry(run, options = {}) { + const maxAttempts = options.maxAttempts ?? defaultMaxAttempts; + const baseDelayMs = options.baseDelayMs ?? defaultBaseDelayMs; + const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))); + const isRetryable = options.isRetryable ?? isRetryableGithubApiError; + const onRetry = options.onRetry; + + let lastError; + for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { + try { + return await run(); + } catch (error) { + lastError = error; + if (attempt === maxAttempts || !isRetryable(error)) { + throw error; + } + const delayMs = baseDelayMs * 2 ** (attempt - 1); + onRetry?.({ attempt, maxAttempts, delayMs, error }); + await sleep(delayMs); + } + } + throw lastError; +} + +module.exports = { + defaultMaxAttempts, + defaultBaseDelayMs, + isRetryableGithubApiStatus, + githubApiErrorStatus, + isRetryableGithubNetworkError, + isRetryableGithubApiError, + withGithubApiRetry, +};