diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000000..b1db98af24f --- /dev/null +++ b/.dockerignore @@ -0,0 +1,16 @@ +# Build context for Containerfile.artifact. Mirrors .npmignore: the build +# needs sources, the shrinkwrap, the scripts that assemble dist/, and the +# command docs that ship in the package (m365 --help reads docs/docs/cmd). +.git +.github +node_modules +dist +allCommands*.json +coverage +.nyc_output +.vscode +.circleci +test-projects +docs/** +!docs/docs/cmd/** +!docs/docs/_clisettings.mdx diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000000..ed3f7944b60 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,39 @@ +name: ci + +# Fork CI. The workflows inherited from upstream (check_pr, release, ...) are +# all gated on `github.repository_owner == 'pnp'` and never run here, so +# without this file the fork ships a production artifact with zero test +# coverage in CI. Same steps as upstream's check_pr build+test legs, on the +# Node major the artifact image is built and consumed with. + +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + build-and-test: + runs-on: ubuntu-latest + timeout-minutes: 30 + env: + CLIMICROSOFT365_NOUPDATE: "1" + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: 22 + cache: npm + + - run: npm ci --ignore-scripts + - run: npm run build + - run: npm run lint + - run: npm run test:test diff --git a/.github/workflows/cleanup-pr-image.yml b/.github/workflows/cleanup-pr-image.yml new file mode 100644 index 00000000000..2eb2134a18c --- /dev/null +++ b/.github/workflows/cleanup-pr-image.yml @@ -0,0 +1,44 @@ +name: cleanup-pr-image + +# Delete the pr- image tag once its pull request closes, so PR +# builds do not pile up in billed GHCR storage. The sha-* / semver / latest +# tags published from the default branch are never touched -- PR pushes only +# ever create pr-. +# +# pull_request_target rather than pull_request because fork PRs get a +# read-only GITHUB_TOKEN on pull_request, which cannot delete package +# versions. pull_request_target is safe here because this workflow never +# checks out or executes PR code. + +on: + pull_request_target: + types: [closed] + +permissions: + packages: write + +jobs: + delete: + runs-on: ubuntu-latest + env: + # Keep in step with the image matrix in the publish-image workflow. + IMAGES: m365-cli + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PR_NUMBER: ${{ github.event.number }} + steps: + - name: Delete pr-${{ github.event.number }} package versions + run: | + for image in $IMAGES; do + ids=$(gh api "orgs/${{ github.repository_owner }}/packages/container/${image}/versions" \ + --paginate \ + --jq ".[] | select(.metadata.container.tags[]? == \"pr-${PR_NUMBER}\") | .id") + if [ -z "$ids" ]; then + echo "No pr-${PR_NUMBER} version of ${image} to delete." + continue + fi + for id in $ids; do + echo "Deleting ${image} version ${id} (pr-${PR_NUMBER})" + gh api --method DELETE \ + "orgs/${{ github.repository_owner }}/packages/container/${image}/versions/${id}" + done + done diff --git a/.github/workflows/prune-images.yml b/.github/workflows/prune-images.yml new file mode 100644 index 00000000000..5b7bb2c521b --- /dev/null +++ b/.github/workflows/prune-images.yml @@ -0,0 +1,87 @@ +name: prune-images + +# Weekly registry hygiene: delete package versions that are MAX_AGE_DAYS old +# or older and are either +# - tagged only pr-* : images whose close-time cleanup was missed, or for +# open PRs untouched for a month -- the next push to such a PR simply +# republishes its image, or +# - untagged : orphaned digests that escaped the inline superseded- +# digest deletion in publish-pr-image (e.g. a run that failed mid-push). +# +# sha-*, semver and latest tags are never deleted regardless of age, and any +# digest referenced as a child of a *tagged* index is skipped, so this stays +# safe if builds ever go multi-arch (GHCR lists index children as untagged +# versions). +# +# Note: GitHub suspends cron workflows after ~60 days without repository +# activity; a push re-arms them. + +on: + schedule: + - cron: "17 3 * * 1" # Mondays 03:17 UTC + workflow_dispatch: + inputs: + dry_run: + description: Only report what would be deleted + type: boolean + default: true + +jobs: + prune: + runs-on: ubuntu-latest + permissions: + packages: write + env: + # Keep in step with the image matrix in the publish-image workflow. + IMAGES: m365-cli + MAX_AGE_DAYS: 30 + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # Empty on scheduled runs, which therefore delete for real. + DRY_RUN: ${{ inputs.dry_run }} + steps: + - name: Prune old PR images and orphans + run: | + set -euo pipefail + owner="${{ github.repository_owner }}" + cutoff=$(date -u -d "${MAX_AGE_DAYS} days ago" +%s) + echo "$GH_TOKEN" | skopeo login ghcr.io --username "${{ github.actor }}" --password-stdin + + for image in $IMAGES; do + versions=$(gh api "orgs/${owner}/packages/container/${image}/versions" --paginate) + + # Digests referenced by any tagged index must survive, or the + # tagged image breaks. + protected=$(echo "$versions" \ + | jq -r '.[] | select(.metadata.container.tags | length > 0) | .name' \ + | while read -r digest; do + skopeo inspect --raw "docker://ghcr.io/${owner}/${image}@${digest}" \ + | jq -r '.manifests[]?.digest // empty' + done | sort -u) + + candidates=$(echo "$versions" | jq -r --argjson cutoff "$cutoff" ' + .[] + | select((.updated_at | fromdateiso8601) <= $cutoff) + | select((.metadata.container.tags | length == 0) + or (.metadata.container.tags | all(startswith("pr-")))) + | "\(.id)\t\(.name)\t\(.metadata.container.tags | join(","))"') + + if [ -z "$candidates" ]; then + echo "${image}: nothing ${MAX_AGE_DAYS}+ days old to prune." + continue + fi + + while IFS=$'\t' read -r id name tags; do + [ -z "$id" ] && continue + if [ -n "$protected" ] && echo "$protected" | grep -qx "$name"; then + echo "${image}: keeping ${name} (child of a tagged index)" + continue + fi + if [ "$DRY_RUN" = "true" ]; then + echo "${image}: DRY RUN, would delete version ${id} (${tags:-untagged}) ${name}" + else + echo "${image}: deleting version ${id} (${tags:-untagged}) ${name}" + gh api --method DELETE \ + "orgs/${owner}/packages/container/${image}/versions/${id}" + fi + done <<< "$candidates" + done diff --git a/.github/workflows/publish-image.yml b/.github/workflows/publish-image.yml new file mode 100644 index 00000000000..1f10a1bfeea --- /dev/null +++ b/.github/workflows/publish-image.yml @@ -0,0 +1,155 @@ +name: publish-image + +# Build this fork's artifact image (Containerfile.artifact: a FROM scratch +# image containing only the built m365 package tree at /opt/m365) and publish +# it to the organisation's private GitHub Container Registry as +# ghcr.io/rh-forge/m365-cli. +# +# Consumers pin it by tag *and* digest, e.g. in rh-forge/openclaw-saw-image: +# ARG M365_IMAGE=ghcr.io/rh-forge/m365-cli:sha-@sha256: +# so sha- tags must be immutable: the guard step below refuses to +# publish a commit whose sha- tag already exists. A re-run must never +# re-point sha- at a new digest -- the old digest would become +# untagged and prune-images would delete it, breaking every pinned consumer. +# There is deliberately no semver/tag trigger here for the same reason: this +# fork cuts no releases, and every published artifact maps 1:1 to a commit. +# +# Pull requests build the image and hand it off as an OCI-archive artifact +# instead of pushing. The publish-pr-image workflow (workflow_run) picks the +# artifact up and pushes it as pr-. The split exists because +# GITHUB_TOKEN is downgraded to read-only on pull_request runs from forks -- +# so this workflow's PR path only ever reads, and the privileged half never +# executes PR code. PR builds publish only pr-, so unreviewed images +# stay clearly labelled and never enter the sha-* namespace. +# +# `latest` tracks the default branch. Nothing should pin it. + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +# GITHUB_TOKEN can push to ghcr.io for repositories in this organisation, so +# no PAT and no organisation secret is needed. +permissions: + contents: read + packages: write + +concurrency: + group: publish-image-${{ github.ref }} + cancel-in-progress: true + +env: + IMAGE: m365-cli + REGISTRY_IMAGE: ghcr.io/${{ github.repository_owner }}/m365-cli + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + + - uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3 + + - name: Log in to ghcr.io + if: github.event_name != 'pull_request' + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Refuse to republish an existing sha- tag + if: github.event_name != 'pull_request' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + echo "$GH_TOKEN" | skopeo login ghcr.io --username "${{ github.actor }}" --password-stdin + ref="docker://${REGISTRY_IMAGE}:sha-${GITHUB_SHA}" + if digest=$(skopeo inspect --no-tags --format '{{.Digest}}' "$ref" 2>/dev/null); then + echo "::error::${REGISTRY_IMAGE}:sha-${GITHUB_SHA} is already published as ${digest}." + echo "::error::sha- tags are immutable (consumers pin them by digest). Push a new commit to publish a new artifact." + exit 1 + fi + echo "No existing artifact for sha-${GITHUB_SHA}; proceeding." + + - id: meta + name: Derive tags and OCI labels + uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5 + with: + images: ${{ env.REGISTRY_IMAGE }} + tags: | + type=sha,format=long,prefix=sha- + type=raw,value=latest,enable={{is_default_branch}} + type=ref,event=pr + labels: | + org.opencontainers.image.title=${{ env.IMAGE }} + + - name: Build and push + id: build + if: github.event_name != 'pull_request' + uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6 + with: + context: . + file: Containerfile.artifact + # Stated, not inherited: a silent runner flip would ship binaries + # that die on the cluster with "Exec format error". + platforms: linux/amd64 + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha,scope=${{ env.IMAGE }} + cache-to: type=gha,mode=max,scope=${{ env.IMAGE }},ignore-error=true + # Suppress the unknown/unknown attestation manifest. With a single + # platform this also makes the pushed object a plain manifest, so + # the digest below is exactly what FROM ...@sha256 needs. + provenance: false + + - name: Record the pin for consumers + if: github.event_name != 'pull_request' + env: + DIGEST: ${{ steps.build.outputs.digest }} + run: | + set -euo pipefail + { + echo "## Published ${REGISTRY_IMAGE}" + echo + echo "Pin (tag and digest):" + echo + echo '```' + echo "${REGISTRY_IMAGE}:sha-${GITHUB_SHA}@${DIGEST}" + echo '```' + echo + echo "Bump the consumer with:" + echo + echo '```' + echo "scripts/bump-tool-pin.sh ${IMAGE} sha-${GITHUB_SHA}" + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + + # Deliberately untagged: each tag becomes a separate entry in the + # archive's index and skopeo then refuses to pick ("more than one + # image in oci"). The destination tag is applied by publish-pr-image. + - name: Build to OCI archive + if: github.event_name == 'pull_request' + uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6 + with: + context: . + file: Containerfile.artifact + platforms: linux/amd64 + outputs: type=oci,dest=/tmp/${{ env.IMAGE }}.tar + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha,scope=${{ env.IMAGE }} + cache-to: type=gha,mode=max,scope=${{ env.IMAGE }},ignore-error=true + provenance: false + + - name: Upload image artifact + if: github.event_name == 'pull_request' + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: pr-image-${{ env.IMAGE }} + path: /tmp/${{ env.IMAGE }}.tar + retention-days: 1 + compression-level: 0 diff --git a/.github/workflows/publish-pr-image.yml b/.github/workflows/publish-pr-image.yml new file mode 100644 index 00000000000..17a1f26be97 --- /dev/null +++ b/.github/workflows/publish-pr-image.yml @@ -0,0 +1,132 @@ +name: publish-pr-image + +# Second half of the PR image pipeline. The publish-image workflow builds PR +# images without credentials and uploads them as OCI archives; this workflow +# runs in the base-repository context (workflow_run), so it holds a real +# GITHUB_TOKEN even when the PR came from a fork, and pushes the archives to +# ghcr.io as pr-. +# +# Deliberately NOT gated on the triggering run's conclusion: a PR image is a +# debugging artifact, and it is most useful exactly when tests fail. The PR +# still fails verification through its own checks; this workflow only ever +# writes the pr- tag, never sha-*/latest/semver, so a failing PR +# cannot contaminate any tag a deployment consumes. If the image build +# itself failed there is simply no artifact, and this run skips cleanly. +# +# Everything taken from the triggering run is untrusted -- the artifact was +# built from unreviewed PR code. This workflow therefore +# - never executes anything from the artifact: skopeo streams it to the +# registry as data, +# - only pushes image names on the hard-coded allowlist below, so a +# malicious PR cannot rename its artifact to overwrite another +# repository's package, and +# - derives the PR number from the head SHA via the API instead of +# trusting anything the PR run wrote. +# +# workflow_run always executes this file as it exists on the default branch, +# never the PR's copy. + +on: + workflow_run: + workflows: [publish-image] + types: [completed] + +permissions: + contents: read + # Download artifacts from the triggering run. + actions: read + # List the PRs associated with the head commit. + pull-requests: read + packages: write + +concurrency: + group: publish-pr-image-${{ github.event.workflow_run.head_repository.full_name }}-${{ github.event.workflow_run.head_branch }} + cancel-in-progress: true + +env: + # Images this workflow is willing to push. Keep in step with the image + # matrix in the publish-image workflow. + ALLOWED_IMAGES: m365-cli + +jobs: + push: + if: > + github.event.workflow_run.event == 'pull_request' && + github.event.workflow_run.conclusion != 'cancelled' + runs-on: ubuntu-latest + steps: + - name: Find the open PR for this head SHA + id: pr + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + HEAD_SHA: ${{ github.event.workflow_run.head_sha }} + run: | + # The SHA-equality filter also drops runs whose PR has since gained + # newer commits -- the newer run, not this one, owns the pr-N tag. + number=$(gh api "repos/${{ github.repository }}/commits/${HEAD_SHA}/pulls" \ + --jq "[.[] | select(.state == \"open\" and .head.sha == \"${HEAD_SHA}\")][0].number // empty") + if [ -z "$number" ]; then + echo "No open PR has ${HEAD_SHA} as its head; nothing to publish." + echo "skip=true" >> "$GITHUB_OUTPUT" + else + echo "number=$number" >> "$GITHUB_OUTPUT" + fi + + - name: Download image artifacts + if: steps.pr.outputs.skip != 'true' + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + pattern: pr-image-* + path: /tmp/pr-images + run-id: ${{ github.event.workflow_run.id }} + github-token: ${{ secrets.GITHUB_TOKEN }} + + - name: Push to ghcr.io + if: steps.pr.outputs.skip != 'true' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PR_NUMBER: ${{ steps.pr.outputs.number }} + run: | + shopt -s nullglob + dirs=(/tmp/pr-images/pr-image-*/) + if [ ${#dirs[@]} -eq 0 ]; then + # The triggering run failed before any image built, or its path + # filters skipped the image jobs. Nothing to publish. + echo "No image artifacts on run ${{ github.event.workflow_run.id }}; skipping." + exit 0 + fi + echo "$GH_TOKEN" | skopeo login ghcr.io --username "${{ github.actor }}" --password-stdin + for dir in "${dirs[@]}"; do + image=$(basename "$dir") + image=${image#pr-image-} + case " $ALLOWED_IMAGES " in + *" $image "*) ;; + *) + echo "::warning::ignoring artifact for unexpected image '$image'" + continue + ;; + esac + dest="ghcr.io/${{ github.repository_owner }}/${image}:pr-${PR_NUMBER}" + + # Remember what pr-N pointed at so the superseded digest can be + # deleted after the tag moves; empty on the PR's first push. + old_digest=$(skopeo inspect --format '{{.Digest}}' --no-tags "docker://${dest}" 2>/dev/null || true) + + skopeo copy "oci-archive:${dir}${image}.tar" "docker://${dest}" + + new_digest=$(skopeo inspect --format '{{.Digest}}' --no-tags "docker://${dest}") + if [ -n "$old_digest" ] && [ "$old_digest" != "$new_digest" ]; then + # Delete exactly the version the tag moved off of, and only if + # nothing else still tags it. Never a blanket untagged purge: + # that would also hit child manifests of any future multi-arch + # index, which are listed as untagged versions. + id=$(gh api "orgs/${{ github.repository_owner }}/packages/container/${image}/versions" \ + --paginate \ + --jq ".[] | select(.name == \"${old_digest}\" and (.metadata.container.tags | length == 0)) | .id") + if [ -n "$id" ]; then + echo "Deleting superseded ${image}@${old_digest} (version ${id})" + gh api --method DELETE \ + "orgs/${{ github.repository_owner }}/packages/container/${image}/versions/${id}" + fi + fi + done diff --git a/Containerfile.artifact b/Containerfile.artifact new file mode 100644 index 00000000000..b1aed79d2e4 --- /dev/null +++ b/Containerfile.artifact @@ -0,0 +1,65 @@ +# Artifact image for the m365 CLI: a FROM scratch image whose only content is +# the CLI installed under the npm global prefix /opt/m365. Consumers +# (rh-forge/openclaw-saw-image) inline it with a digest-pinned +# `FROM ghcr.io/rh-forge/m365-cli:sha-@sha256:... AS m365-artifact` / +# `COPY --from=m365-artifact /opt/m365 /opt/m365` and symlink +# /opt/m365/bin/m365 to /usr/local/bin/m365. The TypeScript build and the +# dependency install happen here, once per fork commit, not in every +# downstream image build. Published by .github/workflows/publish-image.yml. +# +# The tree is arch- and ABI-independent (no native modules), but it is built +# and smoke-tested against Node 22 because that is the consumer's runtime +# major. hi/nodejs only publishes stream tags, so the digest was resolved from +# 22-builder at pin time; re-resolve with +# `skopeo inspect --no-tags --override-os linux --override-arch amd64 \ +# --format '{{.Digest}}' docker://registry.access.redhat.com/hi/nodejs:22-builder` +ARG NODE_IMAGE=registry.access.redhat.com/hi/nodejs:22-builder@sha256:87c55b0b1ca2ef8a0f991ab09742d0d61d7bc16dc258bd45df1fc5b5a535b1f6 + +FROM ${NODE_IMAGE} AS build + +USER 0 +ENV CLIMICROSOFT365_NOUPDATE=1 \ + npm_config_update_notifier=false \ + npm_config_fund=false \ + npm_config_audit=false + +WORKDIR /src + +# Dependencies first, from the shrinkwrap, so a source-only change reuses +# this layer. --ignore-scripts: nothing in the tree needs an install hook +# (protobufjs's postinstall only generates optional helpers), and it keeps +# the fork's "prepare" hook from running a build before sources are copied. +COPY package.json npm-shrinkwrap.json ./ +RUN npm ci --ignore-scripts + +COPY . . + +# Build, then let npm install the packed tarball into its own global prefix: +# `npm pack` applies .npmignore (the single definition of the shipped file +# set: dist/, allCommands*.json, docs/docs/cmd for --help, the completion +# script, package.json, the shrinkwrap), and `npm install --global` from that +# tarball resolves the package's dependencies from the shrinkwrap it carries, +# creates the bin link with the right mode, and needs no tar in the builder +# (the arm64 hi/nodejs builder has none). Layout is npm's standard prefix +# layout: /opt/m365/bin/m365 -> ../lib/node_modules/@pnp/cli-microsoft365/dist/index.js +RUN set -eux; \ + npm run build; \ + npm pack --ignore-scripts --pack-destination /tmp; \ + npm install --global --prefix /opt/m365 --omit=dev --ignore-scripts /tmp/pnp-cli-microsoft365-*.tgz; \ + npm cache clean --force; \ + pkg=/opt/m365/lib/node_modules/@pnp/cli-microsoft365; \ + test -x /opt/m365/bin/m365; \ + test -f "$pkg/allCommands.json"; \ + test -f "$pkg/allCommandsFull.json"; \ + test -d "$pkg/docs/docs/cmd"; \ + test ! -d "$pkg/src"; \ + HOME=/tmp /opt/m365/bin/m365 version; \ + HOME=/tmp /opt/m365/bin/m365 spo site list --help >/dev/null + +FROM scratch + +LABEL org.opencontainers.image.source="https://github.com/rh-forge/cli-microsoft365" +LABEL org.opencontainers.image.description="m365 CLI installed under the npm prefix /opt/m365 (artifact image; needs a Node 22 runtime)" +LABEL org.opencontainers.image.licenses="MIT" + +COPY --from=build /opt/m365 /opt/m365 diff --git a/src/m365/outlook/commands/event/event-list.spec.ts b/src/m365/outlook/commands/event/event-list.spec.ts index 19775b1c3e9..5d40f795acf 100644 --- a/src/m365/outlook/commands/event/event-list.spec.ts +++ b/src/m365/outlook/commands/event/event-list.spec.ts @@ -236,7 +236,7 @@ describe(commands.EVENT_LIST, () => { it('passes validation if neither userId nor userName is specified', () => { const actual = commandOptionsSchema.safeParse({ - id: calendarId + calendarId }); assert.strictEqual(actual.success, true); });