initial import
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
name: Verify TypeScript Build
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v5
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: "pnpm"
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Typecheck
|
||||
run: pnpm run check
|
||||
|
||||
- name: Build bundles
|
||||
run: pnpm run build
|
||||
|
||||
- name: Ensure dist matches bundled output
|
||||
run: |
|
||||
if [[ -n "$(git status --porcelain dist)" ]]; then
|
||||
echo '::error::Detected modified files in dist/ after running pnpm run build. Please rebuild locally and commit the updated bundles.'
|
||||
git --no-pager diff dist
|
||||
exit 1
|
||||
fi
|
||||
@@ -0,0 +1,29 @@
|
||||
name: CLA Assistant
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
pull_request_target:
|
||||
types: [opened, closed, synchronize]
|
||||
|
||||
permissions:
|
||||
actions: write
|
||||
contents: write
|
||||
pull-requests: write
|
||||
statuses: write
|
||||
|
||||
jobs:
|
||||
cla:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: contributor-assistant/[email protected]
|
||||
if: |
|
||||
github.event_name == 'pull_request_target' ||
|
||||
github.event.comment.body == 'recheck' ||
|
||||
github.event.comment.body == 'I have read the CLA Document and I hereby sign the CLA'
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
path-to-document: https://github.com/openai/codex-exec-action-internal/blob/main/CLA.md
|
||||
path-to-signatures: signatures/cla.json
|
||||
branch: cla-signatures
|
||||
allowlist: dependabot[bot]
|
||||
@@ -0,0 +1,2 @@
|
||||
/node_modules/
|
||||
*.log
|
||||
@@ -0,0 +1,44 @@
|
||||
# Individual Contributor License Agreement (v1.0, OpenAI)
|
||||
|
||||
_Based on the Apache Software Foundation Individual CLA v 2.2._
|
||||
|
||||
By commenting **“I have read the CLA Document and I hereby sign the CLA”**
|
||||
on a Pull Request, **you (“Contributor”) agree to the following terms** for any
|
||||
past and future “Contributions” submitted to the **OpenAI Codex CLI project
|
||||
(the “Project”)**.
|
||||
|
||||
---
|
||||
|
||||
## 1. Definitions
|
||||
- **“Contribution”** – any original work of authorship submitted to the Project
|
||||
(code, documentation, designs, etc.).
|
||||
- **“You” / “Your”** – the individual (or legal entity) posting the acceptance
|
||||
comment.
|
||||
|
||||
## 2. Copyright License
|
||||
You grant **OpenAI, Inc.** and all recipients of software distributed by the
|
||||
Project a perpetual, worldwide, non‑exclusive, royalty‑free, irrevocable
|
||||
license to reproduce, prepare derivative works of, publicly display, publicly
|
||||
perform, sublicense, and distribute Your Contributions and derivative works.
|
||||
|
||||
## 3. Patent License
|
||||
You grant **OpenAI, Inc.** and all recipients of the Project a perpetual,
|
||||
worldwide, non‑exclusive, royalty‑free, irrevocable (except as below) patent
|
||||
license to make, have made, use, sell, offer to sell, import, and otherwise
|
||||
transfer Your Contributions alone or in combination with the Project.
|
||||
|
||||
If any entity brings patent litigation alleging that the Project or a
|
||||
Contribution infringes a patent, the patent licenses granted by You to that
|
||||
entity under this CLA terminate.
|
||||
|
||||
## 4. Representations
|
||||
1. You are legally entitled to grant the licenses above.
|
||||
2. Each Contribution is either Your original creation or You have authority to
|
||||
submit it under this CLA.
|
||||
3. Your Contributions are provided **“AS IS”** without warranties of any kind.
|
||||
4. You will notify the Project if any statement above becomes inaccurate.
|
||||
|
||||
## 5. Miscellany
|
||||
This Agreement is governed by the laws of the **State of California**, USA,
|
||||
excluding its conflict‑of‑laws rules. If any provision is held unenforceable,
|
||||
the remaining provisions remain in force.
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. 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.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor 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
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You 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 the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You 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 such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its 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. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2025 OpenAI
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,13 @@
|
||||
Copyright 2025 OpenAI
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,85 @@
|
||||
# Codex Exec GitHub Action
|
||||
|
||||
Run [`codex exec`](https://github.com/openai/codex#codex-exec) directly from a GitHub Actions workflow while keeping tight control over the privileges available to Codex. This action handles installing the Codex CLI, starting the required proxy to the OpenAI Responses API, and cleaning up after execution so you can focus on the prompt you want to run.
|
||||
|
||||
## Quick Start
|
||||
|
||||
```yaml
|
||||
name: Run Codex Exec
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
prompt:
|
||||
description: Prompt to send to Codex
|
||||
required: true
|
||||
|
||||
jobs:
|
||||
codex:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
|
||||
- name: Run Codex
|
||||
uses: openai/codex-exec-action@main
|
||||
id: codex
|
||||
with:
|
||||
openai_api_key: ${{ secrets.OPENAI_API_KEY }}
|
||||
prompt: ${{ github.event.inputs.prompt }}
|
||||
```
|
||||
|
||||
Provide either `prompt` or `prompt_file`; the other may be left empty. The action streams Codex output to the job logs and exposes the final message as an output named `final_message` for downstream steps.
|
||||
|
||||
## Inputs
|
||||
|
||||
| Name | Required | Description | Default |
|
||||
| ------------------------- | ------------- | -------------------------------------------------------------------------------------------------------------- | ---------------- |
|
||||
| `openai_api_key` | Yes | Secret used to authenticate the helper proxy with OpenAI. Store it in `secrets` and never hardcode it. | — |
|
||||
| `prompt` | Conditionally | Inline prompt text. Provide this or `prompt_file`. | `""` |
|
||||
| `prompt_file` | Conditionally | Path (relative to the repository root) of a file that contains the prompt. Provide this or `prompt`. | `""` |
|
||||
| `codex_working_directory` | No | Directory passed to `codex exec --cd`. Defaults to the repository root. | `""` |
|
||||
| `codex_version` | No | Version of `@openai/codex` to install. | `0.42.0-alpha.3` |
|
||||
| `codex_args` | No | Extra arguments forwarded to `codex exec`. Accepts JSON arrays (`["--flag", "value"]`) or shell-style strings. | `""` |
|
||||
| `codex_output_file` | No | File where the final Codex message is written. Leave empty to skip writing a file. | `""` |
|
||||
| `codex_home` | No | Directory to use as the Codex CLI home (config/cache). Uses the CLI default when empty. | `""` |
|
||||
| `safety_strategy` | No | Controls how the action restricts Codex privileges. See [Safety strategy](#safety-strategy). | `drop_sudo` |
|
||||
| `codex_user` | No | Username to run Codex as when `safety_strategy` is `unprivileged_user`. | `""` |
|
||||
|
||||
## Safety Strategy
|
||||
|
||||
The `safety_strategy` input determines how much access Codex receives on the runner. Choosing the right option is critical, especially when sensitive secrets (like your OpenAI API key) are present.
|
||||
|
||||
- **`drop_sudo` (default)** — On Linux and macOS runners, the action revokes the default user’s `sudo` membership before invoking Codex. Codex then runs as that user without superuser privileges. This change lasts for the rest of the job, so subsequent steps cannot rely on `sudo`. This is usually the safest choice on GitHub-hosted runners.
|
||||
- **`unprivileged_user`** — Runs Codex as the user provided via `codex_user`. Use this if you manage your own runner with a pre-created unprivileged account. Ensure the user can read the repository checkout and any files Codex needs.
|
||||
- **`read_only`** — Executes Codex in a read-only sandbox. Codex can view files but cannot mutate the filesystem or access the network directly. The OpenAI API key still flows through the proxy, so Codex could read it if it can reach process memory.
|
||||
- **`unsafe`** — No privilege reduction. Codex runs as the default `runner` user (which typically has `sudo`). Only use this when you fully trust the prompt. On Windows runners this is the only supported choice and the action will fail if another option is provided.
|
||||
|
||||
### Operating system support
|
||||
|
||||
- **Windows**: GitHub-hosted Windows runners lack a supported sandbox. Set `safety_strategy: unsafe`. The action validates this and exits early otherwise.
|
||||
- **Linux/macOS**: All options for `safety_strategy` are supported. Again, if you pick `drop_sudo`, remember that later steps in your `job` that rely on `sudo` will fail. If you do need to run code that requires `sudo` after `openai/codex-exec-action` has run, one option is to pipe the output of `openai/codex-exec-action` to a fresh `job` on a new host and to continue your workflow from there.
|
||||
|
||||
## Outputs
|
||||
|
||||
| Name | Description |
|
||||
| --------------- | --------------------------------------- |
|
||||
| `final_message` | Final message returned by `codex exec`. |
|
||||
|
||||
You can reference the output from later steps:
|
||||
|
||||
```yaml
|
||||
# steps.codex refers to the `id: codex` step in the above example.
|
||||
- name: Capture Codex result
|
||||
run: echo "Codex said: ${{ steps.codex.outputs.final_message }}"
|
||||
```
|
||||
|
||||
Replace `steps.codex` with the `id` assigned to your action step.
|
||||
|
||||
## Additional tips
|
||||
|
||||
- Run this action after `actions/checkout@v5` so Codex has access to your repository contents.
|
||||
- If you want Codex to have access to a narrow set of privileged functionality, consider running a local MCP server that can perform these actions and configure Codex to use it.
|
||||
- If you need more control over the CLI invocation, pass flags through `codex_args` or create a `config.toml` in `codex_home`.
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the [Apache License 2.0](./LICENSE)
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
name: "Codex Exec Action"
|
||||
description: "Run `codex exec` with a prompt."
|
||||
author: "OpenAI"
|
||||
inputs:
|
||||
prompt:
|
||||
description: "Prompt to pass to `codex exec`. `prompt` or `prompt_file` must be provided."
|
||||
required: false
|
||||
default: ""
|
||||
prompt_file:
|
||||
description: "Path to file that contains the prompt to pass to `codex exec`. `prompt` or `prompt_file` must be provided."
|
||||
required: false
|
||||
default: ""
|
||||
openai_api_key:
|
||||
description: "OpenAI API key used by the Codex CLI."
|
||||
required: true
|
||||
codex_working_directory:
|
||||
description: "Optional working directory to `cd` into before running `codex exec`."
|
||||
required: false
|
||||
default: ""
|
||||
codex_version:
|
||||
description: "Version of `@openai/codex` to install."
|
||||
required: false
|
||||
default: "0.43.0-alpha.3"
|
||||
codex_args:
|
||||
description: "Additional args to pass through to `codex exec`. If this value starts with `[`, it will be parsed as a JSON array; otherwise, it will be parsed as a shell-like string."
|
||||
required: false
|
||||
default: ""
|
||||
codex_output_file:
|
||||
description: "File path where the Codex output should be written. Ignored if the empty string."
|
||||
required: false
|
||||
default: ""
|
||||
codex_home:
|
||||
description: "Directory to use as the Codex home directory. If empty, the default Codex home directory will be used."
|
||||
required: false
|
||||
default: ""
|
||||
safety_strategy:
|
||||
description: |
|
||||
Specify one of the following options (on Windows, the only supported option is `unsafe`):
|
||||
|
||||
* `drop_sudo` (default, IRREVERSIBLE) Drop sudo privileges (if any) from
|
||||
the default user before running Codex, and run Codex as that user. This
|
||||
is only supported on Linux and macOS runners. This option is
|
||||
irreversible: if the default user has sudo privileges, they will be
|
||||
removed permanently for the duration of the job.
|
||||
* `unprivileged_user` Run Codex as the specified user specified by the
|
||||
`codex_user` option (the user must already exist). Note the caller is
|
||||
responsible for ensuring the specified user has the privileges it needs
|
||||
to perform the requested actions. For example, the copy of the repo
|
||||
created by `actions/checkout` is not world-readable by default.
|
||||
* `read_only` Run Codex in a sandbox that can read any file on disk,
|
||||
but cannot write to disk or access the network. Note Codex will still
|
||||
run as the default user for this Action, which likely has sudo
|
||||
privileges, so it could read `openai_api_key` from memory and reveal it
|
||||
by printing it to the output of the GitHub Action.
|
||||
* `unsafe` (NOT RECOMMENDED) Do not try to restrict Codex's privileges at all.
|
||||
This is extremely dangerous, as the default user for this Action likely
|
||||
has sudo privileges, which means it can read secrets stored in memory
|
||||
(such as the value of `openai_api_key`) and print them to the output
|
||||
of the GitHub Action or exfiltrate them in other ways.
|
||||
required: false
|
||||
default: "drop_sudo"
|
||||
codex_user:
|
||||
description: "If `safety_strategy` is set to `unprivileged_user`, this specifies the UNIX username to run Codex as."
|
||||
required: false
|
||||
default: ""
|
||||
require_repo_write:
|
||||
description: "Whether to require the triggering actor to have write access to the repository before running."
|
||||
required: false
|
||||
default: "true"
|
||||
allow_bots:
|
||||
description: "Allow runs triggered by GitHub Apps/bot accounts to bypass the write-access check."
|
||||
required: false
|
||||
default: "false"
|
||||
outputs:
|
||||
final_message:
|
||||
description: "Raw output emitted by `codex exec`."
|
||||
value: ${{ steps.run_codex.outputs.final_message }}
|
||||
runs:
|
||||
using: "composite"
|
||||
steps:
|
||||
- name: Validate Windows safety strategy
|
||||
if: ${{ runner.os == 'Windows' }}
|
||||
shell: bash
|
||||
run: |
|
||||
if [ "${{ inputs.safety_strategy }}" != "unsafe" ]; then
|
||||
echo "On Windows, inputs.safety_strategy must be 'unsafe'" >&2
|
||||
echo "because no viable sandboxing options are available at this time." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Ensure Node.js available
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "20"
|
||||
|
||||
- name: Check repository write access
|
||||
if: ${{ inputs.require_repo_write == 'true' }}
|
||||
env:
|
||||
ALLOW_BOTS: ${{ inputs.allow_bots }}
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
shell: bash
|
||||
run: |
|
||||
node --enable-source-maps dist/main.js check-write-access --allow-bots "$ALLOW_BOTS"
|
||||
|
||||
- name: Install Codex CLI
|
||||
shell: bash
|
||||
run: npm install -g "@openai/codex@${{ inputs.codex_version }}"
|
||||
|
||||
- name: Install Codex Responses API proxy
|
||||
shell: bash
|
||||
run: npm install -g "@openai/codex-responses-api-proxy@${{ inputs.codex_version }}"
|
||||
|
||||
- name: Start Responses API proxy
|
||||
id: start_proxy
|
||||
env:
|
||||
OPENAI_API_KEY: ${{ inputs.openai_api_key }}
|
||||
shell: bash
|
||||
run: |
|
||||
tmpfile=$(mktemp)
|
||||
(
|
||||
printenv OPENAI_API_KEY | codex-responses-api-proxy --http-shutdown --server-info "$tmpfile"
|
||||
) &
|
||||
for _ in {1..10}; do
|
||||
if [ -s "$tmpfile" ]; then
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
if [ ! -s "$tmpfile" ]; then
|
||||
echo "responses-api-proxy did not write server info" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "server_info_file=$tmpfile" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# This step has an output named `port`.
|
||||
- name: Read server info
|
||||
id: read_server_info
|
||||
shell: bash
|
||||
run: node dist/main.js read-server-info "${{ steps.start_proxy.outputs.server_info_file }}"
|
||||
|
||||
- name: Drop sudo privilege, if appropriate
|
||||
if: ${{ inputs.safety_strategy == 'drop_sudo' }}
|
||||
shell: bash
|
||||
run: |
|
||||
case "${RUNNER_OS}" in
|
||||
Linux)
|
||||
node --enable-source-maps dist/main.js drop-sudo --user runner --group sudo
|
||||
;;
|
||||
macOS)
|
||||
node --enable-source-maps dist/main.js drop-sudo --user runner --group admin
|
||||
;;
|
||||
*)
|
||||
echo "Unsupported OS for drop_sudo: ${RUNNER_OS}" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
- name: Verify sudo privilege removed
|
||||
if: ${{ inputs.safety_strategy == 'drop_sudo' }}
|
||||
shell: bash
|
||||
run: |
|
||||
if sudo -n true 2>/dev/null; then
|
||||
echo "Expected sudo to be disabled, but sudo succeeded." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Confirmed sudo privilege is disabled."
|
||||
|
||||
- name: Run codex exec
|
||||
id: run_codex
|
||||
env:
|
||||
CODEX_PROMPT: ${{ inputs.prompt }}
|
||||
CODEX_PROMPT_FILE: ${{ inputs.prompt_file }}
|
||||
CODEX_HOME: ${{ inputs.codex_home }}
|
||||
CODEX_WORKING_DIRECTORY: ${{ inputs.codex_working_directory || github.workspace }}
|
||||
CODEX_ARGS: ${{ inputs.codex_args }}
|
||||
CODEX_OUTPUT_FILE: ${{ inputs.codex_output_file }}
|
||||
CODEX_SAFETY_STRATEGY: ${{ inputs.safety_strategy }}
|
||||
CODEX_USER: ${{ inputs.codex_user }}
|
||||
shell: bash
|
||||
run: |
|
||||
node --enable-source-maps dist/main.js run-codex-exec \
|
||||
--prompt "${CODEX_PROMPT}" \
|
||||
--prompt-file "${CODEX_PROMPT_FILE}" \
|
||||
--codex-home "$CODEX_HOME" \
|
||||
--cd "$CODEX_WORKING_DIRECTORY" \
|
||||
--proxy-port "${{ steps.read_server_info.outputs.port }}" \
|
||||
--extra-args "$CODEX_ARGS" \
|
||||
--output-file "$CODEX_OUTPUT_FILE" \
|
||||
--safety-strategy "$CODEX_SAFETY_STRATEGY" \
|
||||
--codex-user "$CODEX_USER"
|
||||
|
||||
- name: Shutdown codex webserver
|
||||
env:
|
||||
CODEX_SERVER_PORT: ${{ steps.read_server_info.outputs.port }}
|
||||
shell: bash
|
||||
run: curl --fail --silent --show-error "http://127.0.0.1:${CODEX_SERVER_PORT}/shutdown"
|
||||
Vendored
+27597
File diff suppressed because one or more lines are too long
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "@openai/codex-exec-action",
|
||||
"version": "0.0.0",
|
||||
"description": "GitHub Action to run codex exec via the Codex CLI with accompanying helper steps",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "esbuild src/main.ts --sourcemap=inline --format=cjs --bundle --platform=node --target=node20 --outdir=dist",
|
||||
"check": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.11.1",
|
||||
"@octokit/graphql": "^8.2.2",
|
||||
"@octokit/rest": "^21.1.1",
|
||||
"commander": "14.0.1",
|
||||
"string-argv": "0.3.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.12.7",
|
||||
"esbuild": "^0.23.0",
|
||||
"typescript": "^5.4.5"
|
||||
},
|
||||
"packageManager": "[email protected]"
|
||||
}
|
||||
Generated
+507
@@ -0,0 +1,507 @@
|
||||
lockfileVersion: '9.0'
|
||||
|
||||
settings:
|
||||
autoInstallPeers: true
|
||||
excludeLinksFromLockfile: false
|
||||
|
||||
importers:
|
||||
|
||||
.:
|
||||
dependencies:
|
||||
'@actions/core':
|
||||
specifier: ^1.11.1
|
||||
version: 1.11.1
|
||||
'@octokit/graphql':
|
||||
specifier: ^8.2.2
|
||||
version: 8.2.2
|
||||
'@octokit/rest':
|
||||
specifier: ^21.1.1
|
||||
version: 21.1.1
|
||||
commander:
|
||||
specifier: 14.0.1
|
||||
version: 14.0.1
|
||||
string-argv:
|
||||
specifier: 0.3.2
|
||||
version: 0.3.2
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
specifier: ^20.12.7
|
||||
version: 20.12.7
|
||||
esbuild:
|
||||
specifier: ^0.23.0
|
||||
version: 0.23.0
|
||||
typescript:
|
||||
specifier: ^5.4.5
|
||||
version: 5.4.5
|
||||
|
||||
packages:
|
||||
|
||||
'@actions/[email protected]':
|
||||
resolution: {integrity: sha512-hXJCSrkwfA46Vd9Z3q4cpEpHB1rL5NG04+/rbqW9d3+CSvtB1tYe8UTpAlixa1vj0m/ULglfEK2UKxMGxCxv5A==}
|
||||
|
||||
'@actions/[email protected]':
|
||||
resolution: {integrity: sha512-+sCcHHbVdk93a0XT19ECtO/gIXoxvdsgQLzb2fE2/5sIZmWQuluYyjPQtrtTHdU1YzTZ7bAPN4sITq2xi1679w==}
|
||||
|
||||
'@actions/[email protected]':
|
||||
resolution: {integrity: sha512-mx8hyJi/hjFvbPokCg4uRd4ZX78t+YyRPtnKWwIl+RzNaVuFpQHfmlGVfsKEJN8LwTCvL+DfVgAM04XaHkm6bA==}
|
||||
|
||||
'@actions/[email protected]':
|
||||
resolution: {integrity: sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q==}
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-3sG8Zwa5fMcA9bgqB8AfWPQ+HFke6uD3h1s3RIwUNK8EG7a4buxvuFTs3j1IMs2NXAk9F30C/FF4vxRgQCcmoQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [ppc64]
|
||||
os: [aix]
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-EuHFUYkAVfU4qBdyivULuu03FhJO4IJN9PGuABGrFy4vUuzk91P2d+npxHcFdpUnfYKy0PuV+n6bKIpHOB3prQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [android]
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-+KuOHTKKyIKgEEqKbGTK8W7mPp+hKinbMBeEnNzjJGyFcWsfrXjSTNluJHCY1RqhxFurdD8uNXQDei7qDlR6+g==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm]
|
||||
os: [android]
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-WRrmKidLoKDl56LsbBMhzTTBxrsVwTKdNbKDalbEZr0tcsBgCLbEtoNthOW6PX942YiYq8HzEnb4yWQMLQuipQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [android]
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-YLntie/IdS31H54Ogdn+v50NuoWF5BDkEUFpiOChVa9UnKpftgwzZRrI4J132ETIi+D8n6xh9IviFV3eXdxfow==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-IMQ6eme4AfznElesHUPDZ+teuGwoRmVuuixu7sv92ZkdQcPbsNHzutd+rAfaBKo8YK3IrBEi9SLLKWJdEvJniQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-0muYWCng5vqaxobq6LB3YNtevDFSAZGlgtLoAc81PjUfiFz36n4KMpwhtAd4he8ToSI3TGyuhyx5xmiWNYZFyw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [freebsd]
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-XKDVu8IsD0/q3foBzsXGt/KjD/yTKBCIwOHE1XwiXmrRwrX6Hbnd5Eqn/WvDekddK21tfszBSrE/WMaZh+1buQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [freebsd]
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-j1t5iG8jE7BhonbsEg5d9qOYcVZv/Rv6tghaXM/Ug9xahM0nX/H2gfu6X6z11QRTMT6+aywOMA8TDkhPo8aCGw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-SEELSTEtOFu5LPykzA395Mc+54RMg1EUgXP+iw2SJ72+ooMwVsgfuwXo5Fn0wXNgWZsTVHwY2cg4Vi/bOD88qw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-P7O5Tkh2NbgIm2R6x1zGJJsnacDzTFcRWZyTTMgFdVit6E98LTxO+v8LCCLWRvPrjdzXHx9FEOA8oAZPyApWUA==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [ia32]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-InQwepswq6urikQiIC/kkx412fqUZudBO4SYKu0N+tGhXRWUqAx+Q+341tFV6QdBifpjYgUndV1hhMq3WeJi7A==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [loong64]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-J9rflLtqdYrxHv2FqXE2i1ELgNjT+JFURt/uDMoPQLcjWQA5wDKgQA4t/dTqGa88ZVECKaD0TctwsUfHbVoi4w==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [mips64el]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-cShCXtEOVc5GxU0fM+dsFD10qZ5UpcQ8AM22bYj0u/yaAykWnqXJDpd77ublcX6vdDsWLuweeuSNZk4yUxZwtw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [ppc64]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-HEtaN7Y5UB4tZPeQmgz/UhzoEyYftbMXrBCUjINGjh3uil+rB/QzzpMshz3cNUxqXN7Vr93zzVtpIDL99t9aRw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-WDi3+NVAuyjg/Wxi+o5KPqRbZY0QhI9TjrEEm+8dmpY9Xir8+HE/HNx2JoLckhKbFopW0RdO2D72w8trZOV+Wg==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [s390x]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-a3pMQhUEJkITgAw6e0bWA+F+vFtCciMjW/LPtoj99MhVt+Mfb6bbL9hu2wmTZgNd994qTAEw+U/r6k3qHWWaOQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-cRK+YDem7lFTs2Q5nEv/HHc4LnrfBCbH5+JHu6wm2eP+d8OZNoSMYgPZJq78vqQ9g+9+nMuIsAO7skzphRXHyw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [netbsd]
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-suXjq53gERueVWu0OKxzWqk7NxiUWSUlrxoZK7usiF50C6ipColGR5qie2496iKGYNLhDZkPxBI3erbnYkU0rQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [openbsd]
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-6p3nHpby0DM/v15IFKMjAaayFhqnXV52aEmv1whZHX56pdkK+MEaLoQWj+H42ssFarP1PcomVhbsR4pkz09qBg==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [openbsd]
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-BFelBGfrBwk6LVrmFzCq1u1dZbG4zy/Kp93w2+y83Q5UGYF1d8sCzeLI9NXjKyujjBBniQa8R8PzLFAUrSM9OA==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [sunos]
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-lY6AC8p4Cnb7xYHuIxQ6iYPe6MfO2CC43XXKo9nBXDb35krYt7KGhQnOkRGar5psxYkircpCqfbNDB4uJbS2jQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [win32]
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-7L1bHlOTcO4ByvI7OXVI5pNN6HSu6pUQq9yodga8izeuB1KcT2UkHaH6118QJwopExPn0rMHIseCTx1CRo/uNA==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [ia32]
|
||||
os: [win32]
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
resolution: {integrity: sha512-Arm+WgUFLUATuoxCJcahGuk6Yj9Pzxd6l11Zb/2aAuv5kWWvvfhLFo2fni4uSK5vzlUdCGZ/BdV5tH8klj8p8g==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
|
||||
'@fastify/[email protected]':
|
||||
resolution: {integrity: sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA==}
|
||||
engines: {node: '>=14'}
|
||||
|
||||
'@octokit/[email protected]':
|
||||
resolution: {integrity: sha512-JcQDsBdg49Yky2w2ld20IHAlwr8d/d8N6NiOXbtuoPCqzbsiJgF633mVUw3x4mo0H5ypataQIX7SFu3yy44Mpw==}
|
||||
engines: {node: '>= 18'}
|
||||
|
||||
'@octokit/[email protected]':
|
||||
resolution: {integrity: sha512-kIU8SLQkYWGp3pVKiYzA5OSaNF5EE03P/R8zEmmrG6XwOg5oBjXyQVVIauQ0dgau4zYhpZEhJrvIYt6oM+zZZA==}
|
||||
engines: {node: '>= 18'}
|
||||
|
||||
'@octokit/[email protected]':
|
||||
resolution: {integrity: sha512-OlYOlZIsfEVZm5HCSR8aSg02T2lbUWOsCQoPKfTXJwDzcHQBrVBGdGXb89dv2Kw2ToZaRtudp8O3ZIYoaOjKlA==}
|
||||
engines: {node: '>= 18'}
|
||||
|
||||
'@octokit/[email protected]':
|
||||
resolution: {integrity: sha512-Yi8hcoqsrXGdt0yObxbebHXFOiUA+2v3n53epuOg1QUgOB6c4XzvisBNVXJSl8RYA5KrDuSL2yq9Qmqe5N0ryA==}
|
||||
engines: {node: '>= 18'}
|
||||
|
||||
'@octokit/[email protected]':
|
||||
resolution: {integrity: sha512-9sIH3nSUttelJSXUrmGzl7QUBFul0/mB8HRYl3fOlgHbIWG+WnYDXU3v/2zMtAvuzZ/ed00Ei6on975FhBfzrg==}
|
||||
|
||||
'@octokit/[email protected]':
|
||||
resolution: {integrity: sha512-idsIggNXUKkk0+BExUn1dQ92sfysJrje03Q0bv0e+KPLrvyqZF8MnBpFz8UNfYDwB3Ie7Z0TByjWfzxt7vseaA==}
|
||||
|
||||
'@octokit/[email protected]':
|
||||
resolution: {integrity: sha512-n5KPteiF7pWKgBIBJSk8qzoZWcUkza2O6A0za97pMGVrGfPdltxrfmfF5GucHYvHGZD8BdaZmmHGz5cX/3gdpw==}
|
||||
engines: {node: '>= 18'}
|
||||
peerDependencies:
|
||||
'@octokit/core': '>=6'
|
||||
|
||||
'@octokit/[email protected]':
|
||||
resolution: {integrity: sha512-n/lNeCtq+9ofhC15xzmJCNKP2BWTv8Ih2TTy+jatNCCq/gQP/V7rK3fjIfuz0pDWDALO/o/4QY4hyOF6TQQFUw==}
|
||||
engines: {node: '>= 18'}
|
||||
peerDependencies:
|
||||
'@octokit/core': '>=6'
|
||||
|
||||
'@octokit/[email protected]':
|
||||
resolution: {integrity: sha512-9Pas60Iv9ejO3WlAX3maE1+38c5nqbJXV5GrncEfkndIpZrJ/WPMRd2xYDcPPEt5yzpxcjw9fWNoPhsSGzqKqw==}
|
||||
engines: {node: '>= 18'}
|
||||
peerDependencies:
|
||||
'@octokit/core': '>=6'
|
||||
|
||||
'@octokit/[email protected]':
|
||||
resolution: {integrity: sha512-WEi/R0Jmq+IJKydWlKDmryPcmdYSVjL3ekaiEL1L9eo1sUnqMJ+grqmC9cjk7CA7+b2/T397tO5d8YLOH3qYpQ==}
|
||||
engines: {node: '>= 18'}
|
||||
|
||||
'@octokit/[email protected]':
|
||||
resolution: {integrity: sha512-q8ybdytBmxa6KogWlNa818r0k1wlqzNC+yNkcQDECHvQo8Vmstrg18JwqJHdJdUiHD2sjlwBgSm9kHkOKe2iyA==}
|
||||
engines: {node: '>= 18'}
|
||||
|
||||
'@octokit/[email protected]':
|
||||
resolution: {integrity: sha512-sTQV7va0IUVZcntzy1q3QqPm/r8rWtDCqpRAmb8eXXnKkjoQEtFe3Nt5GTVsHft+R6jJoHeSiVLcgcvhtue/rg==}
|
||||
engines: {node: '>= 18'}
|
||||
|
||||
'@octokit/[email protected]':
|
||||
resolution: {integrity: sha512-ifLaO34EbbPj0Xgro4G5lP5asESjwHracYJvVaPIyXMuiuXLlhic3S47cBdTb+jfODkTE5YtGCLt3Ay3+J97sA==}
|
||||
|
||||
'@octokit/[email protected]':
|
||||
resolution: {integrity: sha512-1y6DgTy8Jomcpu33N+p5w58l6xyt55Ar2I91RPiIA0xCJBXyUAhXCcmZaDWSANiha7R9a6qJJ2CRomGPZ6f46g==}
|
||||
|
||||
'@types/[email protected]':
|
||||
resolution: {integrity: sha512-wq0cICSkRLVaf3UGLMGItu/PtdY7oaXaI/RVU+xliKVOtRna3PRY57ZDfztpDL0n11vfymMUnXv8QwYCO7L1wg==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-Nik3Sc0ncrMK4UUdXQmAnRtzmNQTAAXmXIopizwZ1W1t8QmfJj+zL4OA2I7XPTPW5z5TDqv4hRo/JzouDJnX3A==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-2JkV3gUZUVrbNA+1sjBOYLsMZ5cEEl8GTFP2a4AVz5hvasAMCQ1D2l2le/cX+pV4N6ZU17zjUahLpIXRrnWL8A==}
|
||||
engines: {node: '>=20'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-1lvV17H2bMYda/WaFb2jLPeHU3zml2k4/yagNMG8Q/YtfMjCwEUZa2eXXMgZTVSL5q1n4H7sQ0X6CdJDqqeCFA==}
|
||||
engines: {node: '>=18'}
|
||||
hasBin: true
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-nGqtvLrj5w0naR6tDPfB4cUmYCqouzyQiz6C5y/LtcDllJdrcc6WaWW6iXyIIOErTa/XRybj28aasdn4LkVk6Q==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==}
|
||||
engines: {node: '>=0.6.19'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==}
|
||||
engines: {node: '>=0.6.11 <=0.7.0 || >=0.7.3'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==}
|
||||
engines: {node: '>=14.17'}
|
||||
hasBin: true
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-raqeBD6NQK4SkWhQzeYKd1KmIG6dllBOTt55Rmkt4HtI9mwdWtJljnrXjAFUBLTSN67HWrOIZ3EPF4kjUw80Bg==}
|
||||
engines: {node: '>=14.0'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-TmnEAEAsBJVZM/AADELsK76llnwcf9vMKuPz8JflO1frO8Lchitr0fNaN9d+Ap0BjKtqWqd/J17qeDnXh8CL2A==}
|
||||
|
||||
snapshots:
|
||||
|
||||
'@actions/[email protected]':
|
||||
dependencies:
|
||||
'@actions/exec': 1.1.1
|
||||
'@actions/http-client': 2.2.3
|
||||
|
||||
'@actions/[email protected]':
|
||||
dependencies:
|
||||
'@actions/io': 1.1.3
|
||||
|
||||
'@actions/[email protected]':
|
||||
dependencies:
|
||||
tunnel: 0.0.6
|
||||
undici: 5.29.0
|
||||
|
||||
'@actions/[email protected]': {}
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@esbuild/[email protected]':
|
||||
optional: true
|
||||
|
||||
'@fastify/[email protected]': {}
|
||||
|
||||
'@octokit/[email protected]': {}
|
||||
|
||||
'@octokit/[email protected]':
|
||||
dependencies:
|
||||
'@octokit/auth-token': 5.1.2
|
||||
'@octokit/graphql': 8.2.2
|
||||
'@octokit/request': 9.2.4
|
||||
'@octokit/request-error': 6.1.8
|
||||
'@octokit/types': 14.1.0
|
||||
before-after-hook: 3.0.2
|
||||
universal-user-agent: 7.0.3
|
||||
|
||||
'@octokit/[email protected]':
|
||||
dependencies:
|
||||
'@octokit/types': 14.1.0
|
||||
universal-user-agent: 7.0.3
|
||||
|
||||
'@octokit/[email protected]':
|
||||
dependencies:
|
||||
'@octokit/request': 9.2.4
|
||||
'@octokit/types': 14.1.0
|
||||
universal-user-agent: 7.0.3
|
||||
|
||||
'@octokit/[email protected]': {}
|
||||
|
||||
'@octokit/[email protected]': {}
|
||||
|
||||
'@octokit/[email protected](@octokit/[email protected])':
|
||||
dependencies:
|
||||
'@octokit/core': 6.1.6
|
||||
'@octokit/types': 13.10.0
|
||||
|
||||
'@octokit/[email protected](@octokit/[email protected])':
|
||||
dependencies:
|
||||
'@octokit/core': 6.1.6
|
||||
|
||||
'@octokit/[email protected](@octokit/[email protected])':
|
||||
dependencies:
|
||||
'@octokit/core': 6.1.6
|
||||
'@octokit/types': 13.10.0
|
||||
|
||||
'@octokit/[email protected]':
|
||||
dependencies:
|
||||
'@octokit/types': 14.1.0
|
||||
|
||||
'@octokit/[email protected]':
|
||||
dependencies:
|
||||
'@octokit/endpoint': 10.1.4
|
||||
'@octokit/request-error': 6.1.8
|
||||
'@octokit/types': 14.1.0
|
||||
fast-content-type-parse: 2.0.1
|
||||
universal-user-agent: 7.0.3
|
||||
|
||||
'@octokit/[email protected]':
|
||||
dependencies:
|
||||
'@octokit/core': 6.1.6
|
||||
'@octokit/plugin-paginate-rest': 11.6.0(@octokit/[email protected])
|
||||
'@octokit/plugin-request-log': 5.3.1(@octokit/[email protected])
|
||||
'@octokit/plugin-rest-endpoint-methods': 13.5.0(@octokit/[email protected])
|
||||
|
||||
'@octokit/[email protected]':
|
||||
dependencies:
|
||||
'@octokit/openapi-types': 24.2.0
|
||||
|
||||
'@octokit/[email protected]':
|
||||
dependencies:
|
||||
'@octokit/openapi-types': 25.1.0
|
||||
|
||||
'@types/[email protected]':
|
||||
dependencies:
|
||||
undici-types: 5.26.5
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]:
|
||||
optionalDependencies:
|
||||
'@esbuild/aix-ppc64': 0.23.0
|
||||
'@esbuild/android-arm': 0.23.0
|
||||
'@esbuild/android-arm64': 0.23.0
|
||||
'@esbuild/android-x64': 0.23.0
|
||||
'@esbuild/darwin-arm64': 0.23.0
|
||||
'@esbuild/darwin-x64': 0.23.0
|
||||
'@esbuild/freebsd-arm64': 0.23.0
|
||||
'@esbuild/freebsd-x64': 0.23.0
|
||||
'@esbuild/linux-arm': 0.23.0
|
||||
'@esbuild/linux-arm64': 0.23.0
|
||||
'@esbuild/linux-ia32': 0.23.0
|
||||
'@esbuild/linux-loong64': 0.23.0
|
||||
'@esbuild/linux-mips64el': 0.23.0
|
||||
'@esbuild/linux-ppc64': 0.23.0
|
||||
'@esbuild/linux-riscv64': 0.23.0
|
||||
'@esbuild/linux-s390x': 0.23.0
|
||||
'@esbuild/linux-x64': 0.23.0
|
||||
'@esbuild/netbsd-x64': 0.23.0
|
||||
'@esbuild/openbsd-arm64': 0.23.0
|
||||
'@esbuild/openbsd-x64': 0.23.0
|
||||
'@esbuild/sunos-x64': 0.23.0
|
||||
'@esbuild/win32-arm64': 0.23.0
|
||||
'@esbuild/win32-ia32': 0.23.0
|
||||
'@esbuild/win32-x64': 0.23.0
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
'@fastify/busboy': 2.1.1
|
||||
|
||||
[email protected]: {}
|
||||
@@ -0,0 +1,135 @@
|
||||
import * as core from "@actions/core";
|
||||
import { Octokit } from "@octokit/rest";
|
||||
|
||||
export type WriteAccessCheck =
|
||||
| {
|
||||
status: "approved";
|
||||
actor: string;
|
||||
}
|
||||
| {
|
||||
status: "rejected";
|
||||
actor: string;
|
||||
reason: string;
|
||||
};
|
||||
|
||||
type EnsureWriteAccessOptions = {
|
||||
octokit?: Octokit;
|
||||
token?: string;
|
||||
actor?: string;
|
||||
repository?: string;
|
||||
/**
|
||||
* When true (default), bot actors such as dependabot are allowed without
|
||||
* checking collaborator permissions. Set to false to require bots to pass the
|
||||
* same checks as human users.
|
||||
*/
|
||||
allowBotActors?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks that the GitHub actor which triggered the current workflow has write
|
||||
* access to the repository.
|
||||
*/
|
||||
export async function ensureActorHasWriteAccess(
|
||||
options: EnsureWriteAccessOptions = {},
|
||||
): Promise<WriteAccessCheck> {
|
||||
const actor = options.actor ?? process.env.GITHUB_ACTOR;
|
||||
const repository = options.repository ?? process.env.GITHUB_REPOSITORY;
|
||||
const allowBotActors = options.allowBotActors ?? true;
|
||||
|
||||
if (!actor || actor.trim().length === 0) {
|
||||
return {
|
||||
status: "rejected",
|
||||
actor: actor ?? "<unknown>",
|
||||
reason: "GITHUB_ACTOR is not set; cannot determine triggering user.",
|
||||
};
|
||||
}
|
||||
|
||||
if (!repository || repository.trim().length === 0) {
|
||||
return {
|
||||
status: "rejected",
|
||||
actor,
|
||||
reason: "GITHUB_REPOSITORY is not set; cannot determine target repository.",
|
||||
};
|
||||
}
|
||||
|
||||
const [owner, repo] = repository.split("/");
|
||||
if (!owner || !repo) {
|
||||
return {
|
||||
status: "rejected",
|
||||
actor,
|
||||
reason: `GITHUB_REPOSITORY must be in the format 'owner/repo', received: '${repository}'.`,
|
||||
};
|
||||
}
|
||||
|
||||
// GitHub-built workflows (e.g. dependabot, github-actions[bot]) do not have a
|
||||
// meaningful write permission concept. They implicitly run with the token's permissions.
|
||||
if (allowBotActors && actor.endsWith("[bot]")) {
|
||||
core.info(`Actor '${actor}' is a bot account; skipping explicit permission check.`);
|
||||
return { status: "approved", actor };
|
||||
}
|
||||
|
||||
const token = options.token ?? getTokenFromEnv();
|
||||
if (!token) {
|
||||
return {
|
||||
status: "rejected",
|
||||
actor,
|
||||
reason: "A GitHub token is required to check permissions (set GITHUB_TOKEN or GH_TOKEN).",
|
||||
};
|
||||
}
|
||||
|
||||
const octokit = options.octokit ?? new Octokit({ auth: token });
|
||||
|
||||
core.info(`Checking write access for actor '${actor}' on ${owner}/${repo}`);
|
||||
|
||||
let permission: string;
|
||||
try {
|
||||
const response = await octokit.repos.getCollaboratorPermissionLevel({
|
||||
owner,
|
||||
repo,
|
||||
username: actor,
|
||||
});
|
||||
permission = response.data.permission ?? "none";
|
||||
} catch (error) {
|
||||
if (isNotFoundError(error)) {
|
||||
return {
|
||||
status: "rejected",
|
||||
actor,
|
||||
reason: `Actor '${actor}' is not a collaborator on ${owner}/${repo}; write access is required.`,
|
||||
};
|
||||
}
|
||||
|
||||
const message =
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Failed to verify permissions for actor due to unknown error.";
|
||||
|
||||
return {
|
||||
status: "rejected",
|
||||
actor,
|
||||
reason: `Failed to verify permissions for '${actor}': ${message}`,
|
||||
};
|
||||
}
|
||||
|
||||
core.info(`Actor '${actor}' has permission level '${permission}'.`);
|
||||
|
||||
if (permission === "admin" || permission === "write" || permission === "maintain") {
|
||||
return { status: "approved", actor };
|
||||
}
|
||||
|
||||
return {
|
||||
status: "rejected",
|
||||
actor,
|
||||
reason: `Actor '${actor}' must have write access to ${owner}/${repo}. Detected permission: '${permission}'.`,
|
||||
};
|
||||
}
|
||||
|
||||
function getTokenFromEnv(): string {
|
||||
const token = process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN;
|
||||
return token && token.trim().length > 0 ? token : "";
|
||||
}
|
||||
|
||||
function isNotFoundError(error: unknown): boolean {
|
||||
return Boolean(
|
||||
error && typeof error === "object" && "status" in error && (error as { status?: number }).status === 404,
|
||||
);
|
||||
}
|
||||
+342
@@ -0,0 +1,342 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { promises as fs } from "node:fs";
|
||||
import * as path from "node:path";
|
||||
|
||||
interface ExecOptions {
|
||||
capture?: boolean;
|
||||
ignoreFailure?: boolean;
|
||||
}
|
||||
|
||||
interface ExecResult {
|
||||
code: number;
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
}
|
||||
|
||||
export interface DropSudoOptions {
|
||||
user: string;
|
||||
group: string;
|
||||
rootPhase: boolean;
|
||||
}
|
||||
|
||||
const LINUX_PLATFORM = "linux";
|
||||
const MACOS_PLATFORM = "darwin";
|
||||
|
||||
export async function dropSudo(options: DropSudoOptions): Promise<void> {
|
||||
const platform = process.platform;
|
||||
if (![LINUX_PLATFORM, MACOS_PLATFORM].includes(platform)) {
|
||||
throw new Error(
|
||||
`Unsupported OS for drop_sudo safety strategy: ${platform}`
|
||||
);
|
||||
}
|
||||
|
||||
const { rootPhase } = options;
|
||||
if (rootPhase) {
|
||||
await dropSudoWithPrivileges(options);
|
||||
return;
|
||||
}
|
||||
|
||||
await ensurePasswordlessSudo();
|
||||
// `sudo -K` invalidates cached credentials but exits non-zero when no ticket
|
||||
// exists yet. Ignore that failure so fresh runners don't blow up.
|
||||
await execCommand("sudo", ["-K"], { ignoreFailure: true });
|
||||
|
||||
const execArgs = [...process.execArgv];
|
||||
const scriptPath = process.argv[1];
|
||||
// Re-enter this command under sudo so the privilege-dropping work happens in a
|
||||
// single place regardless of the host platform.
|
||||
await execCommand("sudo", [
|
||||
"-n",
|
||||
"node",
|
||||
...execArgs,
|
||||
scriptPath,
|
||||
"drop-sudo",
|
||||
"--root-phase",
|
||||
"--user",
|
||||
options.user,
|
||||
"--group",
|
||||
options.group,
|
||||
]);
|
||||
|
||||
// Invalidate the sudo ticket again; ignore failures for the same reason as
|
||||
// above (some environments return an error when no timestamp exists).
|
||||
await execCommand("sudo", ["-K"], { ignoreFailure: true });
|
||||
}
|
||||
|
||||
async function dropSudoWithPrivileges(options: DropSudoOptions): Promise<void> {
|
||||
if (typeof process.getuid === "function" && process.getuid() !== 0) {
|
||||
throw new Error("drop-sudo root phase must run as root.");
|
||||
}
|
||||
|
||||
let changed = false;
|
||||
|
||||
switch (process.platform) {
|
||||
case LINUX_PLATFORM: {
|
||||
if (await isUserInGroup(options.user, options.group)) {
|
||||
if (await commandExists("deluser")) {
|
||||
await execCommand("deluser", [options.user, options.group]);
|
||||
console.log(
|
||||
`Used 'deluser ${options.user} ${options.group}' to drop sudo privilege.`
|
||||
);
|
||||
} else if (await commandExists("gpasswd")) {
|
||||
await execCommand("gpasswd", ["-d", options.user, options.group]);
|
||||
console.log(
|
||||
`Used 'gpasswd -d ${options.user} ${options.group}' to drop sudo privilege.`
|
||||
);
|
||||
} else {
|
||||
throw new Error("Neither deluser nor gpasswd available.");
|
||||
}
|
||||
changed = true;
|
||||
} else {
|
||||
console.log(
|
||||
`${options.user} is not a member of the ${options.group} group.`
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case MACOS_PLATFORM: {
|
||||
if (await isUserInGroup(options.user, options.group)) {
|
||||
await execCommand("dseditgroup", [
|
||||
"-o",
|
||||
"edit",
|
||||
"-d",
|
||||
options.user,
|
||||
"-t",
|
||||
"user",
|
||||
options.group,
|
||||
]);
|
||||
console.log(
|
||||
`Used 'dseditgroup -o edit -d ${options.user} -t user ${options.group}' to drop sudo privilege.`
|
||||
);
|
||||
changed = true;
|
||||
} else {
|
||||
console.log(
|
||||
`${options.user} is not a member of the ${options.group} group.`
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
throw new Error(
|
||||
`Unsupported OS for drop_sudo safety strategy: ${process.platform}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const messages = await removeUserFromSudoersD(options.user);
|
||||
if (messages.length > 0) {
|
||||
for (const message of messages) {
|
||||
console.log(message);
|
||||
}
|
||||
changed = true;
|
||||
} else {
|
||||
console.log(
|
||||
`No ${options.user} entries found in /etc/sudoers.d requiring changes.`
|
||||
);
|
||||
}
|
||||
|
||||
const sudoersMessage = await stripUserEntriesFromFile(
|
||||
"/etc/sudoers",
|
||||
options.user
|
||||
);
|
||||
if (sudoersMessage) {
|
||||
console.log(sudoersMessage);
|
||||
changed = true;
|
||||
} else {
|
||||
console.log(
|
||||
`No ${options.user} entries found in /etc/sudoers requiring changes.`
|
||||
);
|
||||
}
|
||||
|
||||
if (!changed) {
|
||||
console.log(`${options.user} already lacks sudo privileges.`);
|
||||
}
|
||||
|
||||
const groupsAfter = await execCommand("id", ["-Gn", options.user], {
|
||||
capture: true,
|
||||
});
|
||||
console.log(
|
||||
`Groups for ${options.user} after cleanup: ${groupsAfter.stdout.trim()}`
|
||||
);
|
||||
}
|
||||
|
||||
async function ensurePasswordlessSudo(): Promise<void> {
|
||||
try {
|
||||
await execCommand("sudo", ["-n", "true"], { capture: true });
|
||||
} catch (error) {
|
||||
throw new Error("Unexpected: passwordless sudo not available.");
|
||||
}
|
||||
}
|
||||
|
||||
async function isUserInGroup(user: string, group: string): Promise<boolean> {
|
||||
const result = await execCommand("id", ["-nG", user], {
|
||||
capture: true,
|
||||
ignoreFailure: true,
|
||||
});
|
||||
if (result.code !== 0) {
|
||||
return false;
|
||||
}
|
||||
const groups = result.stdout
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.filter((value) => value.length > 0);
|
||||
return groups.includes(group);
|
||||
}
|
||||
|
||||
async function commandExists(binary: string): Promise<boolean> {
|
||||
const result = await execCommand("sh", ["-c", `command -v ${binary}`], {
|
||||
capture: true,
|
||||
ignoreFailure: true,
|
||||
});
|
||||
return result.code === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Strips non-comment entries granting sudo to `user` across `/etc/sudoers.d`
|
||||
* files.
|
||||
*
|
||||
* Strategy:
|
||||
* - enumerate regular files under `/etc/sudoers.d`
|
||||
* - remove lines whose first token matches the target user while keeping
|
||||
* comments/blank lines intact
|
||||
* - rewrite files in-place with original newline style and permissions
|
||||
* - report which files were changed so callers can surface useful logs
|
||||
*/
|
||||
async function removeUserFromSudoersD(user: string): Promise<Array<string>> {
|
||||
const sudoersDir = "/etc/sudoers.d";
|
||||
let entries: Array<string> = [];
|
||||
try {
|
||||
const dirEntries = await fs.readdir(sudoersDir, { withFileTypes: true });
|
||||
entries = dirEntries
|
||||
.filter((dirent) => dirent.isFile())
|
||||
.map((dirent) => path.join(sudoersDir, dirent.name));
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
||||
return [];
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const messages: Array<string> = [];
|
||||
|
||||
for (const entryPath of entries) {
|
||||
const message = await stripUserEntriesFromFile(entryPath, user);
|
||||
if (message) {
|
||||
messages.push(message);
|
||||
}
|
||||
}
|
||||
|
||||
return messages;
|
||||
}
|
||||
|
||||
async function stripUserEntriesFromFile(
|
||||
filePath: string,
|
||||
user: string
|
||||
): Promise<string | null> {
|
||||
let stats;
|
||||
let original: string;
|
||||
try {
|
||||
stats = await fs.stat(filePath);
|
||||
original = await fs.readFile(filePath, "utf8");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
const newline = original.includes("\r\n") ? "\r\n" : "\n";
|
||||
const endsWithNewline =
|
||||
original.endsWith("\n") || original.endsWith("\r\n");
|
||||
const rawLines = original.split(/\r?\n/);
|
||||
if (rawLines.length > 0 && rawLines[rawLines.length - 1] === "") {
|
||||
rawLines.pop();
|
||||
}
|
||||
|
||||
const filteredLines: Array<string> = [];
|
||||
let changed = false;
|
||||
|
||||
for (const line of rawLines) {
|
||||
const trimmedLeading = line.trimStart();
|
||||
if (trimmedLeading.startsWith("#")) {
|
||||
filteredLines.push(line);
|
||||
continue;
|
||||
}
|
||||
if (trimmedLeading.length === 0) {
|
||||
filteredLines.push(line);
|
||||
continue;
|
||||
}
|
||||
const tokens = trimmedLeading.split(/\s+/);
|
||||
if (tokens[0] === user) {
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
filteredLines.push(line);
|
||||
}
|
||||
|
||||
if (!changed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const rebuilt = filteredLines.join(newline) + (endsWithNewline ? newline : "");
|
||||
try {
|
||||
await fs.writeFile(filePath, rebuilt, "utf8");
|
||||
await fs.chmod(filePath, stats.mode & 0o777);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
return `Removed ${user} entry from ${filePath}`;
|
||||
}
|
||||
|
||||
async function execCommand(
|
||||
command: string,
|
||||
args: Array<string>,
|
||||
options: ExecOptions = {}
|
||||
): Promise<ExecResult> {
|
||||
const capture = options.capture ?? false;
|
||||
const child = spawn(command, args, {
|
||||
stdio: capture ? ["ignore", "pipe", "pipe"] : "inherit",
|
||||
});
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
|
||||
if (capture && child.stdout) {
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stdout.on("data", (chunk) => {
|
||||
stdout += chunk;
|
||||
});
|
||||
}
|
||||
|
||||
if (capture && child.stderr) {
|
||||
child.stderr.setEncoding("utf8");
|
||||
child.stderr.on("data", (chunk) => {
|
||||
stderr += chunk;
|
||||
});
|
||||
}
|
||||
|
||||
return await new Promise<ExecResult>((resolve, reject) => {
|
||||
child.on("error", (error) => {
|
||||
reject(error);
|
||||
});
|
||||
|
||||
child.on("close", (code) => {
|
||||
const exitCode = code ?? 0;
|
||||
if (exitCode !== 0 && !options.ignoreFailure) {
|
||||
const error = new Error(
|
||||
`Command failed: ${command} ${args.join(" ")} (exit code ${exitCode})`
|
||||
);
|
||||
(error as ExecError).code = exitCode;
|
||||
(error as ExecError).stdout = stdout;
|
||||
(error as ExecError).stderr = stderr;
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve({ code: exitCode, stdout, stderr });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
interface ExecError extends Error {
|
||||
code: number;
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
}
|
||||
+213
@@ -0,0 +1,213 @@
|
||||
import { Command, Option } from "commander";
|
||||
import pkg from "../package.json" assert { type: "json" };
|
||||
|
||||
import { readServerInfo } from "./readServerInfo";
|
||||
import { PromptSource, runCodexExec, SafetyStrategy } from "./runCodexExec";
|
||||
import { dropSudo } from "./dropSudo";
|
||||
import { ensureActorHasWriteAccess } from "./checkActorPermissions";
|
||||
import parseArgsStringToArgv from "string-argv";
|
||||
|
||||
export async function main() {
|
||||
const program = new Command();
|
||||
|
||||
program
|
||||
.name("codex-exec-action")
|
||||
.version(pkg.version)
|
||||
.description("Multitool to support @openai/codex-exec-action.");
|
||||
|
||||
program
|
||||
.command("read-server-info")
|
||||
.description("Read server info from the responses API proxy")
|
||||
.argument("<serverInfoFile>", "Path to the server info file")
|
||||
.action(async (serverInfoFile: string) => {
|
||||
await readServerInfo(serverInfoFile);
|
||||
});
|
||||
|
||||
program
|
||||
.command("drop-sudo")
|
||||
.description("Drops sudo privileges for the configured user.")
|
||||
.addOption(new Option("--user <user>", "User to modify").default("runner"))
|
||||
.addOption(
|
||||
new Option("--group <group>", "Group granting sudo privileges").default(
|
||||
"sudo"
|
||||
)
|
||||
)
|
||||
.addOption(new Option("--root-phase", "internal").default(false).hideHelp())
|
||||
.action(
|
||||
async (options: { user: string; group: string; rootPhase: boolean }) => {
|
||||
await dropSudo({
|
||||
user: options.user,
|
||||
group: options.group,
|
||||
rootPhase: options.rootPhase,
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
program
|
||||
.command("run-codex-exec")
|
||||
.description("Invokes `codex exec` with the appropriate arguments")
|
||||
.requiredOption("--prompt <prompt>", "Prompt to pass to `codex exec`.")
|
||||
.requiredOption(
|
||||
"--prompt-file <FILE>",
|
||||
"File containing the prompt to pass to `codex exec`."
|
||||
)
|
||||
.requiredOption(
|
||||
"--codex-home <DIRECTORY>",
|
||||
"Path to the Codex CLI home directory (where config files are stored)."
|
||||
)
|
||||
.requiredOption("--cd <DIRECTORY>", "Working directory for Codex")
|
||||
.requiredOption(
|
||||
"--proxy-port <port>",
|
||||
"Port of the Responses API Proxy",
|
||||
parseIntStrict
|
||||
)
|
||||
.requiredOption(
|
||||
"--extra-args <args>",
|
||||
"Additional args to pass through to `codex exec` as JSON array or shell string.",
|
||||
parseExtraArgs
|
||||
)
|
||||
.requiredOption(
|
||||
"--output-file <FILE>",
|
||||
"Path where the final message from `codex exec` will be written."
|
||||
)
|
||||
.requiredOption(
|
||||
"--safety-strategy <strategy>",
|
||||
"Safety strategy to use. One of 'drop_sudo', 'read_only', 'unprivileged_user', or 'unsafe'."
|
||||
)
|
||||
.requiredOption(
|
||||
"--codex-user <user>",
|
||||
"User to run codex exec as when using the 'unprivileged_user' safety strategy."
|
||||
)
|
||||
.action(
|
||||
async (options: {
|
||||
prompt: string;
|
||||
promptFile: string;
|
||||
codexHome: string;
|
||||
cd: string;
|
||||
proxyPort: number;
|
||||
extraArgs: Array<string>;
|
||||
outputFile: string;
|
||||
safetyStrategy: string;
|
||||
codexUser: string;
|
||||
}) => {
|
||||
const {
|
||||
prompt,
|
||||
promptFile,
|
||||
codexHome,
|
||||
cd,
|
||||
proxyPort,
|
||||
extraArgs,
|
||||
outputFile,
|
||||
safetyStrategy,
|
||||
codexUser,
|
||||
} = options;
|
||||
|
||||
const normalizedPrompt = emptyAsNull(prompt);
|
||||
const normalizedPromptFile = emptyAsNull(promptFile);
|
||||
let promptSource: PromptSource;
|
||||
if (normalizedPrompt != null) {
|
||||
promptSource = { type: "text", content: normalizedPrompt };
|
||||
} else if (normalizedPromptFile != null) {
|
||||
promptSource = { type: "file", path: normalizedPromptFile };
|
||||
} else {
|
||||
throw new Error(
|
||||
"Either `prompt` or `prompt_file` must be specified."
|
||||
);
|
||||
}
|
||||
|
||||
// Custom option processing to coerces to null does not work with
|
||||
// Commander.js's requiredOption, so we have to post-process here.
|
||||
await runCodexExec({
|
||||
prompt: promptSource,
|
||||
codexHome: emptyAsNull(codexHome),
|
||||
cd,
|
||||
proxyPort,
|
||||
extraArgs,
|
||||
explicitOutputFile: emptyAsNull(outputFile),
|
||||
safetyStrategy: toSafetyStrategy(safetyStrategy),
|
||||
codexUser: emptyAsNull(codexUser),
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
program
|
||||
.command("check-write-access")
|
||||
.description(
|
||||
"Checks that the triggering actor has write access to the repository"
|
||||
)
|
||||
.option(
|
||||
"--allow-bots <boolean>",
|
||||
"Allow GitHub App and bot actors to bypass the write-access check (default: true).",
|
||||
parseBoolean,
|
||||
true
|
||||
)
|
||||
.action(async ({ allowBots }: { allowBots: boolean }) => {
|
||||
const result = await ensureActorHasWriteAccess({
|
||||
allowBotActors: allowBots,
|
||||
});
|
||||
switch (result.status) {
|
||||
case "approved": {
|
||||
console.log(`Actor '${result.actor}' is permitted to continue.`);
|
||||
break;
|
||||
}
|
||||
case "rejected": {
|
||||
const message = `Actor '${result.actor}' is not permitted to run this action: ${result.reason}`;
|
||||
console.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
program.parse();
|
||||
}
|
||||
|
||||
function parseIntStrict(value: string): number {
|
||||
const parsed = parseInt(value, 10);
|
||||
if (isNaN(parsed)) {
|
||||
throw new Error(`Invalid integer: ${value}`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function parseExtraArgs(value: string): Array<string> {
|
||||
if (value.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (value.startsWith("[")) {
|
||||
return JSON.parse(value);
|
||||
} else {
|
||||
return parseArgsStringToArgv(value);
|
||||
}
|
||||
}
|
||||
|
||||
function toSafetyStrategy(value: string): SafetyStrategy {
|
||||
switch (value) {
|
||||
case "drop_sudo":
|
||||
case "read_only":
|
||||
case "unprivileged_user":
|
||||
case "unsafe":
|
||||
return value;
|
||||
default:
|
||||
throw new Error(
|
||||
`Invalid safety strategy: ${value}. Must be one of 'drop_sudo', 'read_only', 'unprivileged_user', or 'unsafe'.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function emptyAsNull(value: string): string | null {
|
||||
return value.trim().length == 0 ? null : value;
|
||||
}
|
||||
|
||||
function parseBoolean(value: string): boolean {
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (["true", "1", "yes", "y"].includes(normalized)) {
|
||||
return true;
|
||||
}
|
||||
if (["false", "0", "no", "n"].includes(normalized)) {
|
||||
return false;
|
||||
}
|
||||
throw new Error(`Invalid boolean value: ${value}`);
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,30 @@
|
||||
import * as core from "@actions/core";
|
||||
import * as fs from "fs/promises";
|
||||
|
||||
/**
|
||||
* In theory, this is not called until `serverInfoFile` is non-empty, but we
|
||||
* will poll in the rare case that it was a partial write.
|
||||
*/
|
||||
export async function readServerInfo(serverInfoFile: string): Promise<void> {
|
||||
for (let attempt = 0; attempt < 100; attempt++) {
|
||||
try {
|
||||
const contents = await fs.readFile(serverInfoFile, { encoding: "utf8" });
|
||||
const { port } = JSON.parse(contents);
|
||||
if (typeof port !== "number") {
|
||||
continue;
|
||||
}
|
||||
|
||||
core.setOutput("port", port.toString());
|
||||
return;
|
||||
} catch (error) {
|
||||
console.error(`Error reading server info: ${error}`);
|
||||
await sleep(100);
|
||||
}
|
||||
}
|
||||
|
||||
throw Error(`Failed to read server info from ${serverInfoFile}`);
|
||||
}
|
||||
|
||||
async function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import { spawn } from "child_process";
|
||||
import { mkdtemp, readFile, rm } from "fs/promises";
|
||||
import path from "path";
|
||||
import { setOutput } from "@actions/core";
|
||||
|
||||
export type PromptSource =
|
||||
| {
|
||||
type: "text";
|
||||
content: string;
|
||||
}
|
||||
| {
|
||||
type: "file";
|
||||
path: string;
|
||||
};
|
||||
|
||||
export type SafetyStrategy =
|
||||
| "drop_sudo"
|
||||
| "read_only"
|
||||
| "unprivileged_user"
|
||||
| "unsafe";
|
||||
|
||||
export async function runCodexExec({
|
||||
prompt,
|
||||
codexHome,
|
||||
cd,
|
||||
proxyPort,
|
||||
extraArgs,
|
||||
explicitOutputFile,
|
||||
safetyStrategy,
|
||||
codexUser,
|
||||
}: {
|
||||
prompt: PromptSource;
|
||||
codexHome: string | null;
|
||||
cd: string;
|
||||
proxyPort: number;
|
||||
extraArgs: Array<string>;
|
||||
explicitOutputFile: string | null;
|
||||
safetyStrategy: SafetyStrategy;
|
||||
codexUser: string | null;
|
||||
}): Promise<void> {
|
||||
let input: string;
|
||||
switch (prompt.type) {
|
||||
case "text":
|
||||
input = prompt.content;
|
||||
break;
|
||||
case "file":
|
||||
input = await readFile(prompt.path, "utf8");
|
||||
break;
|
||||
}
|
||||
|
||||
let outputFile: OutputFile;
|
||||
if (explicitOutputFile != null) {
|
||||
outputFile = { type: "explicit", file: explicitOutputFile };
|
||||
} else {
|
||||
outputFile = await createTempOutputFile();
|
||||
}
|
||||
|
||||
const command: Array<string> = [];
|
||||
|
||||
if (safetyStrategy === "unprivileged_user") {
|
||||
if (codexUser == null) {
|
||||
throw new Error(
|
||||
"codexUser must be specified when using the 'unprivileged_user' safety strategy."
|
||||
);
|
||||
}
|
||||
|
||||
command.push("sudo", "-u", codexUser, "--");
|
||||
}
|
||||
|
||||
const providerBaseUrl = `http://127.0.0.1:${proxyPort}/v1`;
|
||||
const providerId = "openai-proxy";
|
||||
const providerConfig = `model_providers.${providerId}={ name = "OpenAI Proxy", base_url = "${providerBaseUrl}", wire_api = "responses" }`;
|
||||
|
||||
command.push(
|
||||
"codex",
|
||||
"exec",
|
||||
"--skip-git-repo-check",
|
||||
"--cd",
|
||||
cd,
|
||||
"--config",
|
||||
providerConfig,
|
||||
"--config",
|
||||
`model_provider="${providerId}"`,
|
||||
"--output-last-message",
|
||||
outputFile.file
|
||||
);
|
||||
command.push(...extraArgs);
|
||||
|
||||
// Note that if profiles expand to support their own sandbox policies, a
|
||||
// custom profile could override this setting.
|
||||
if (safetyStrategy === "read_only") {
|
||||
command.push("--config", 'sandbox_mode="read-only"');
|
||||
}
|
||||
|
||||
const env = { ...process.env };
|
||||
let extraEnv = "";
|
||||
if (codexHome != null) {
|
||||
env.CODEX_HOME = codexHome;
|
||||
extraEnv = `CODEX_HOME=${codexHome} `;
|
||||
}
|
||||
|
||||
// Split the `program` from the `args` for `spawn()`.
|
||||
const program = command.shift()!;
|
||||
console.log(
|
||||
`Running: ${extraEnv}${program} ${command
|
||||
.map((a) => JSON.stringify(a))
|
||||
.join(" ")}`
|
||||
);
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(program, command, {
|
||||
env,
|
||||
stdio: ["pipe", "inherit", "inherit"],
|
||||
});
|
||||
child.stdin.write(input);
|
||||
child.stdin.end();
|
||||
|
||||
child.on("error", reject);
|
||||
|
||||
child.on("close", async (code) => {
|
||||
if (code !== 0) {
|
||||
reject(new Error(`${program} exited with code ${code}`));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await finalizeExecution(outputFile);
|
||||
resolve();
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function finalizeExecution(outputFile: OutputFile): Promise<void> {
|
||||
try {
|
||||
const lastMessage = await readFile(outputFile.file, "utf8");
|
||||
setOutput("final_message", lastMessage);
|
||||
} finally {
|
||||
await cleanupTempOutput(outputFile);
|
||||
}
|
||||
}
|
||||
|
||||
type OutputFile =
|
||||
| {
|
||||
type: "explicit";
|
||||
file: string;
|
||||
}
|
||||
| {
|
||||
type: "temp";
|
||||
file: string;
|
||||
};
|
||||
|
||||
async function createTempOutputFile(): Promise<OutputFile> {
|
||||
const dir = await mkdtemp("codex-exec-");
|
||||
return { type: "temp", file: path.join(dir, "output.md") };
|
||||
}
|
||||
|
||||
async function cleanupTempOutput(outputFile: OutputFile): Promise<void> {
|
||||
switch (outputFile.type) {
|
||||
case "explicit":
|
||||
// Do not delete user-specified output files.
|
||||
return;
|
||||
case "temp": {
|
||||
const { file } = outputFile;
|
||||
const dir = path.dirname(file);
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2021",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Node",
|
||||
"resolveJsonModule": true,
|
||||
"esModuleInterop": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
Reference in New Issue
Block a user