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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 124 additions & 0 deletions .github/workflows/opencode-run.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
name: Reusable — opencode run

# Consumers call this via:
#
# jobs:
# run:
# uses: vymalo/opencode-oauth2/.github/workflows/opencode-run.yml@v0.2.0
# with:
# model: miaou/glm-5
# prompt: "Summarize the changes"
# opencode-config-path: .opencode-ci/opencode.json
#
# Consumer must:
# - grant `permissions: { id-token: write, contents: read }` on the caller job
# - commit an opencode.json at `opencode-config-path` with
# `authFlow: "jwt_bearer"` + `subjectTokenSource: { type: "github_actions" }`
# - have an IdP that trusts GitHub Actions OIDC for the configured audience
#
# See docs/github-actions.md for end-to-end setup.

on:
workflow_call:
inputs:
model:
description: 'Model id passed to `opencode run --model` (e.g. miaou/glm-5).'
required: true
type: string
prompt:
description: 'Prompt passed to `opencode run`.'
required: true
type: string
opencode-config-path:
description: 'Path (relative to the repo root) to the opencode.json the runner should use.'
required: false
type: string
default: '.opencode-ci/opencode.json'
node-version:
description: 'Node.js version installed on the runner.'
required: false
type: string
default: '22'
runs-on:
description: 'Runner image. Defaults to ubuntu-latest.'
required: false
type: string
default: 'ubuntu-latest'
opencode-version:
description: 'Pinned `opencode` version to install (npm dist-tag or semver). Empty == latest.'
required: false
type: string
default: ''
plugin-version:
description: 'Pinned `@vymalo/opencode-oauth2` version. Empty == latest.'
required: false
type: string
default: ''
outputs:
stdout-artifact:
description: 'Name of the uploaded artifact containing opencode stdout.'
value: ${{ jobs.run.outputs.stdout-artifact }}

jobs:
run:
name: opencode run
runs-on: ${{ inputs.runs-on }}
permissions:
# OIDC token minting for federated identity (jwt_bearer / token_exchange).
# The caller must also grant id-token: write — workflow_call inherits
# the caller's permissions, but the caller cannot grant more than it has.
id-token: write
contents: read
outputs:
stdout-artifact: opencode-stdout-${{ github.run_id }}-${{ github.run_attempt }}
steps:
- name: Checkout caller repo
uses: actions/checkout@v4

- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ inputs.node-version }}

- name: Install opencode + plugin
run: |
set -euo pipefail
opencode_spec="opencode"
if [ -n "${{ inputs.opencode-version }}" ]; then
opencode_spec="opencode@${{ inputs.opencode-version }}"
fi
plugin_spec="@vymalo/opencode-oauth2"
if [ -n "${{ inputs.plugin-version }}" ]; then
plugin_spec="@vymalo/opencode-oauth2@${{ inputs.plugin-version }}"
fi
npm install -g "$opencode_spec" "$plugin_spec"

- name: Verify opencode config exists
run: |
set -euo pipefail
cfg="${{ inputs.opencode-config-path }}"
if [ ! -f "$cfg" ]; then
echo "::error::opencode config not found at $cfg — commit one (see docs/github-actions.md)" >&2
exit 1
fi
# The config dir is what OPENCODE_CONFIG_DIR points to; opencode will
# read opencode.json from there.
echo "OPENCODE_CONFIG_DIR=$(dirname "$cfg")" >> "$GITHUB_ENV"

- name: opencode run
id: run
run: |
set -euo pipefail
mkdir -p /tmp/opencode-out
opencode run \
--model "${{ inputs.model }}" \
"${{ inputs.prompt }}" \
| tee /tmp/opencode-out/stdout.txt

- name: Upload stdout as artifact
if: always()
uses: actions/upload-artifact@v4
with:
name: opencode-stdout-${{ github.run_id }}-${{ github.run_attempt }}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Make artifact names unique per invocation

In .github/workflows/opencode-run.yml, the uploaded artifact name is derived only from github.run_id and github.run_attempt, so every invocation of this reusable workflow within the same caller workflow run uses the same name. With actions/upload-artifact@v4, artifact names must be unique per run; if a caller uses this reusable workflow in multiple jobs or a matrix, later uploads fail with a conflict error, breaking those jobs even though opencode run succeeded.

Useful? React with 👍 / 👎.

path: /tmp/opencode-out/stdout.txt
if-no-files-found: warn
50 changes: 34 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,39 +11,41 @@ An [OpenCode](https://opencode.ai) plugin that lets you wire up **OpenAI-compati

---

```mermaid
flowchart LR
OC[opencode] -->|chat.headers| Plugin[opencode-oauth2]
Plugin -->|cached token?| Cache[(~/.cache/opencode-oauth2)]
Plugin -->|acquire / refresh| IdP[OAuth server]
Plugin -->|Authorization: Bearer …| Upstream[Provider API]
```

## Why

Most OpenCode providers assume a static bearer key. That works for hosted SaaS, but breaks down the moment you put your models behind:

- a corporate Identity Provider (Keycloak, Auth0, Okta, Azure AD, …)
- a self-hosted gateway with short-lived tokens
- a multi-tenant setup where each user authenticates as themselves
- a CI runner that has no business carrying a long-lived secret

This plugin closes that gap. It handles the **Authorization Code + PKCE** dance, caches tokens, refreshes them silently, and feeds OpenCode a normal-looking provider with a fresh `Authorization` header on every request.
This plugin closes that gap. It handles the OAuth dance for the flow you need, caches tokens, refreshes silently, and feeds OpenCode a normal-looking provider with a fresh `Authorization` header on every request.

## Features

- **Five auth flows**, pick what matches your runtime:
- `authorization_code` — interactive PKCE login (default)
- `device_code` — RFC 8628 device authorization, for browserless user auth
- `device_code` — RFC 8628, for browserless user auth
- `client_credentials` — machine-to-machine with a `clientSecret`
- `jwt_bearer` — RFC 7523 federated identity (GitHub Actions OIDC, Kubernetes SA tokens) — **no long-lived secret in CI**
- `token_exchange` — RFC 8693 federated identity with explicit audience targeting
- **Dynamic model discovery** from `/v1/models` (no hand-maintained model lists)
- **Display-name normalization** so `glm-5` shows up as `GLM 5`
- **Persistent token cache** with automatic refresh
- **`chat.headers` hook** injects bearer tokens per request
- **Strict refresh-token policy** where it makes sense — access-only tokens are rejected by design on user-interactive flows
- **Two configuration styles**: per-provider options or a top-level plugin block

### Running in CI / Kubernetes (no long-lived secrets)

For GitHub Actions and Kubernetes workloads, use the federated identity flows. See the **[Federated identity](packages/opencode-oauth2/README.md#federated-identity-no-long-lived-secrets-in-ci)** section in the package README for end-to-end examples with both `permissions: id-token: write` (GHA) and projected `serviceAccountToken` volumes (K8s).

## Install

In your OpenCode config:

```jsonc
{
"$schema": "https://opencode.ai/config.json",
Expand Down Expand Up @@ -73,17 +75,33 @@ Then declare a provider:
}
```

See [packages/opencode-oauth2/README.md](packages/opencode-oauth2/README.md) for the full configuration reference (including the alternative `pluginConfig.oauth2ModelSync.servers` layout).
See [packages/opencode-oauth2/README.md](packages/opencode-oauth2/README.md) for the **full configuration reference** (including the alternative `pluginConfig.oauth2ModelSync.servers` layout and every optional field).

## Documentation

| Page | When you need it |
| --- | --- |
| [`docs/architecture.md`](docs/architecture.md) | Understand the hooks, token lifecycle per flow, cache layout, sync scheduler, logging |
| [`docs/github-actions.md`](docs/github-actions.md) | CI without stored secrets — Keycloak/Auth0/Okta setup, reusable workflow, matrix, fork-PR limits |
| [`docs/kubernetes.md`](docs/kubernetes.md) | `CronJob` / `Job` / `Deployment` with projected SA tokens, multi-provider pods, RBAC |
| [`docs/local-development.md`](docs/local-development.md) | Sandbox setup, plugin re-export trick, forcing re-auth, dev-only `env` subject token |
| [`docs/troubleshooting.md`](docs/troubleshooting.md) | Symptom-keyed fixes — `redirect_uri_mismatch`, model discovery 403, `invalid_client`, projected-token rotation |

## Federated identity (CI / Kubernetes)

For GitHub Actions and Kubernetes workloads, use `jwt_bearer` (or `token_exchange`) with the platform's own short-lived OIDC token as the subject. The plugin re-fetches it on every access-token expiry; nothing long-lived gets cached.

End-to-end recipes live in [`docs/github-actions.md`](docs/github-actions.md) and [`docs/kubernetes.md`](docs/kubernetes.md). The shipped reusable workflow at [`.github/workflows/opencode-run.yml`](.github/workflows/opencode-run.yml) covers the common `opencode run` case.

## Token Policy

Refresh tokens are **mandatory** — not a nicety.
Refresh tokens are **mandatory** for the flows that issue them.

- Access tokens returned without a `refresh_token` are rejected at exchange time.
- Cached tokens missing `refreshToken` are evicted on load.
- `authorization_code` / `device_code` exchanges that don't return `refresh_token` are rejected.
- Cached tokens missing `refreshToken` are evicted on load (unless they're from `client_credentials` / `jwt_bearer` / `token_exchange`, which don't issue one).
- Refresh responses that omit a new `refresh_token` re-use the existing one.

The intent: a session is either fully renewable or it doesn't get cached. No silent fallbacks to short-lived tokens that fail mid-conversation.
The intent: a user-flow session is either fully renewable or it doesn't get cached. Machine flows re-acquire on every expiry; refresh tokens have no role there.

## Workspace Layout

Expand All @@ -97,7 +115,7 @@ This is a [pnpm](https://pnpm.io) monorepo.

## Development

```bash
```sh
pnpm install
pnpm build
pnpm typecheck
Expand All @@ -106,7 +124,7 @@ pnpm test

Plugin-only iteration:

```bash
```sh
pnpm --filter @vymalo/opencode-oauth2 test
pnpm --filter @vymalo/opencode-oauth2 build
```
Expand Down
Loading