Xpersona
A

authentication-patterns

CLAWHUB · Unverified

Provides auth patterns for API keys, OAuth, and token management

62
Rank
84
Safety
1.6k
Downloads

About

What it does, and when to use it.

Capability contract not published. No trust telemetry is available yet. 1.6K downloads reported by the source. Last updated 10/10/2026.

Avoid when

  • Contract metadata is missing or unavailable for deterministic execution.

Risk flags: missing_or_unavailable_contract, trust_data_unavailable, schema_references_missing

Install and run

Setup complexity: low.

clawhub skill install s17emme0e2m3cpf7k2jvp3a84984b8z9:nm-leyline-authentication-patterns
  1. Install using `clawhub skill install s17emme0e2m3cpf7k2jvp3a84984b8z9:nm-leyline-authentication-patterns` in an isolated environment before connecting it to live workloads.
  2. No published capability contract is available yet, so validate auth and request/response behavior manually.
  3. Review the upstream CLAWHUB listing at https://clawhub.ai/athola/nm-leyline-authentication-patterns before using production credentials.

Contract: missing

curl -s "https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-leyline-authentication-patterns/snapshot"

Run-check

$0.02 USD

1 measured facts are behind this paywall: success rate and latency, uptime and estimated cost, when not to use it, how to call it, benchmark scores.

Agents pay $0.02 in USDC. A card payment is $0.50, the smallest a card allows.

Documentation

CLAWHUB

144,946 characters of source documentation, loaded on request.

Extracted files

5 files captured from the source.

SKILL.md

---
name: authentication-patterns
description: Provides auth patterns for API keys, OAuth, and token management
version: 1.9.8
triggers:
  - authentication
  - api-keys
  - oauth
  - tokens
  - security
  - implementing or reviewing service authentication and credential handling
metadata: {"openclaw": {"homepage": "https://github.com/athola/claude-night-market/tree/master/plugins/leyline", "emoji": "\ud83e\udd9e", "requires": {"config": ["night-market.error-patterns"]}}}
source: claude-night-market
source_plugin: leyline
---

> **Night Market Skill** — ported from [claude-night-market/leyline](https://github.com/athola/claude-night-market/tree/master/plugins/leyline). For the full experience with agents, hooks, and commands, install the Claude Code plugin.


## Table of Contents

- [Overview](#overview)
- [When to Use](#when-to-use)
- [Authentication Methods](#authentication-methods)
- [Quick Start](#quick-start)
- [Verify Authentication](#verify-authentication)
- [Smoke Test](#smoke-test)
- [Standard Flow](#standard-flow)
- [Step 1: Check Environment](#step-1:-check-environment)
- [Step 2: Verify with Service](#step-2:-verify-with-service)
- [Step 3: Handle Failures](#step-3:-handle-failures)
- [Integration Pattern](#integration-pattern)
- [Detailed Resources](#detailed-resources)
- [Exit Criteria](#exit-criteria)


# Authentication Patterns

## Overview

Common authentication patterns for integrating with external services. Provides consistent approaches to credential management, verification, and error handling.

## When To Use

- Integrating with external APIs
- Need credential verification
- Managing multiple auth methods
- Handling auth failures gracefully

## When NOT To Use

- Project doesn't use the leyline infrastructure patterns
- Simple scripts without service architecture needs

## Authentication Methods

| Method | Best For | Environment Variable |
|--------|----------|---------------------|
| API Key | Simple integrations | `{SERVICE}_API_KEY` |
| OAuth | User-authenticated | Browser-based flow |
| Token | Session-based | `{SERVICE}_TOKEN` |
| None | Public APIs | N/A |

## Quick Start

### Verify Authentication
```python
from leyline.auth import verify_auth, AuthMethod

# API Key verification
status = verify_auth(
    service="gemini",
    method=AuthMethod.API_KEY,
    env_var="GEMINI_API_KEY"
)

if not status.authenticated:
    print(f"Auth failed: {status.message}")
    print(f"Action: {status.suggested_action}")
```
**Verification:** Run the command with `--help` flag to verify availability.

### Smoke Test
```python
def verify_with_smoke_test(service: str) -> bool:
    """Verify auth with simple request."""
    result = execute_simple_request(service, "ping")
    return result.success
```
**Verification:** Run `pytest -v` to verify tests pass.

## Standard Flow

### Step 1: Check Environment
```python
def check_credentials(service: str, env_var: str) -> bool:
    value = os.getenv(env_var)
    if not value:
        print(f"Mi

_meta.json

{
  "ownerId": "kn7d107jg9jv602h9ytsegydq184a42s",
  "slug": "nm-leyline-authentication-patterns",
  "version": "1.9.19",
  "publishedAt": 1787750042625
}

modules/auth-methods.md

---
name: auth-methods
description: Detailed authentication method implementations
estimated_tokens: 350
---

# Authentication Methods

## API Key Authentication

### Setup
```bash
# Set in environment
export GEMINI_API_KEY="your-key-here"

# Or in .env file
echo "GEMINI_API_KEY=your-key-here" >> ~/.env
```

### Verification
```python
def verify_api_key(env_var: str) -> AuthStatus:
    key = os.getenv(env_var)

    if not key:
        return AuthStatus(
            authenticated=False,
            message=f"Missing {env_var}",
            suggested_action=f"Set {env_var} environment variable"
        )

    # Validate format (basic check)
    if len(key) < 20:
        return AuthStatus(
            authenticated=False,
            message="API key appears invalid (too short)",
            suggested_action="Verify API key is correct"
        )

    return AuthStatus(authenticated=True)
```

## OAuth Authentication

### Browser Flow
```python
def initiate_oauth(service: str) -> AuthStatus:
    """Start OAuth browser flow."""
    result = subprocess.run(
        [service, "auth", "login"],
        capture_output=True
    )

    if result.returncode == 0:
        return AuthStatus(
            authenticated=True,
            message="OAuth completed successfully"
        )

    return AuthStatus(
        authenticated=False,
        message="OAuth flow failed",
        suggested_action="Check browser, try incognito mode"
    )
```

### Token Storage
```python
# OAuth tokens typically stored by CLI
# Common locations:
# ~/.config/{service}/credentials.json
# ~/.{service}/auth.json
```

## Token Authentication

### Token Refresh
```python
def refresh_token(service: str) -> AuthStatus:
    """Refresh expired token."""
    result = subprocess.run(
        [service, "token", "refresh"],
        capture_output=True
    )

    if result.returncode == 0:
        return AuthStatus(authenticated=True)

    # Token refresh failed, need re-auth
    return AuthStatus(
        authenticated=False,
        message="Token refresh failed",
        suggested_action=f"Run '{service} auth login' to re-authenticate"
    )
```

### Token Validation
```python
def validate_token(token: str) -> bool:
    """Basic token validation."""
    try:
        # JWT tokens have 3 parts
        parts = token.split(".")
        if len(parts) == 3:
            return True
    except:
        pass
    return False
```

## Multi-Method Secondary

```python
def authenticate(service: str, methods: list[AuthMethod]) -> AuthStatus:
    """Try multiple auth methods in order."""
    for method in methods:
        status = verify_auth(service, method)
        if status.authenticated:
            return status

    return AuthStatus(
        authenticated=False,
        message="All authentication methods failed",
        suggested_action="Check credentials and try again"
    )
```

modules/interactive-auth.md

---
name: interactive-auth
description: Interactive authentication with token caching and multi-service support
estimated_tokens: 800
---

# Interactive Authentication

## Overview

Provides interactive authentication flows for external
services with automatic token caching, session management,
and multi-service support.

**Authenticate Once, Use Everywhere**: Tokens are cached
locally and validated efficiently, minimizing interactive
prompts while maintaining security.

**CI/CD Compatible**: Automatically detects non-interactive
environments and falls back to environment variables.

## Quick Start

```bash
source plugins/leyline/scripts/interactive_auth.sh

ensure_auth github || exit 1
gh pr view 123
```

## Configuration

### Environment Variables

| Variable | Purpose | Default |
|----------|---------|---------|
| `AUTH_CACHE_DIR` | Token cache directory | `~/.cache/claude-auth` |
| `AUTH_CACHE_TTL` | Cache TTL in seconds | `300` (5 min) |
| `AUTH_SESSION_TTL` | Session persistence TTL | `86400` (24 hr) |
| `AUTH_INTERACTIVE` | Force interactive mode | `auto` (detect) |
| `AUTH_MAX_ATTEMPTS` | Max authentication attempts | `3` |

### Service-Specific Variables

```bash
export GITHUB_TOKEN="..."               # GitHub fallback
export GITLAB_TOKEN="..."               # GitLab
export AWS_ACCESS_KEY_ID="..."          # AWS
export AWS_SECRET_ACCESS_KEY="..."
export GOOGLE_APPLICATION_CREDENTIALS="path/to/credentials.json"
```

## Core Functions

### `ensure_auth <service>`

Ensure authentication for a service, prompting if
necessary. Returns 0 on success, 1 on failure.

```bash
ensure_auth github || exit 1
ensure_auth gitlab || exit 1
ensure_auth aws || exit 1
```

**Supported services:** `github` (gh), `gitlab` (glab),
`aws`, `gcloud`, `azure`

### `check_auth_status <service>`

Non-interactive check. Returns 0 if authenticated, 1
otherwise.

```bash
if check_auth_status github; then
  echo "GitHub is authenticated"
fi
```

### `invalidate_auth_cache <service>`

Force re-authentication next time.

```bash
invalidate_auth_cache github
ensure_auth github  # Will prompt again
```

### `clear_all_auth_cache`

Clear all cached authentication data across all services.

## Token Caching

Cache structure:

```
~/.cache/claude-auth/
├── github/
│   ├── auth_status.json
│   ├── last_verified.txt
│   └── token_cache.json
├── gitlab/
└── config.json
```

Cache validation uses three mechanisms:

1. **Time-based expiration** (default: 5 minutes)
2. **Session persistence** (default: 24 hours)
3. **Manual invalidation** (via `invalidate_auth_cache`)

Within the cache TTL, `ensure_auth` returns immediately
without contacting the service. After TTL expiry, it
re-validates with the service. After session TTL expiry,
full re-authentication is required.

## Authentication Flows

### GitHub

`ensure_auth github` checks `gh auth status` first,
then cache, then prompts:

1. Browser OAuth (recommended)
2. Personal Access Token
3. Cancel workflow

### AWS

`ensure_auth aws

modules/verification-patterns.md

---
name: verification-patterns
description: Authentication verification and testing patterns
estimated_tokens: 300
---

# Verification Patterns

## Smoke Test

### Simple Request Test
```python
def smoke_test(service: str) -> bool:
    """Test auth with minimal request."""
    try:
        result = subprocess.run(
            [service, "-p", "Respond with OK"],
            capture_output=True,
            timeout=30
        )
        return result.returncode == 0
    except subprocess.TimeoutExpired:
        return False
```

### Model Access Test
```python
def test_model_access(service: str, model: str) -> bool:
    """Verify access to specific model."""
    result = subprocess.run(
        [service, "--model", model, "-p", "ping"],
        capture_output=True
    )
    return result.returncode == 0
```

## Pre-Flight Checks

### Full Verification Flow
```python
def preflight_auth_check(service: str) -> dict:
    """Complete auth verification before operations."""
    checks = {
        "env_var_set": False,
        "cli_available": False,
        "auth_valid": False,
        "model_access": False
    }

    # Check environment variable
    env_var = f"{service.upper()}_API_KEY"
    checks["env_var_set"] = bool(os.getenv(env_var))

    # Check CLI available
    checks["cli_available"] = shutil.which(service) is not None

    # Check auth status
    if checks["cli_available"]:
        result = subprocess.run([service, "auth", "status"], capture_output=True)
        checks["auth_valid"] = result.returncode == 0

    # Check model access
    if checks["auth_valid"]:
        checks["model_access"] = smoke_test(service)

    return checks
```

## Cached Verification

```python
class AuthCache:
    """Cache auth status to avoid repeated checks."""

    def __init__(self, ttl_seconds: int = 300):
        self.cache = {}
        self.ttl = ttl_seconds

    def get_status(self, service: str) -> AuthStatus | None:
        if service in self.cache:
            status, timestamp = self.cache[service]
            if time.time() - timestamp < self.ttl:
                return status
        return None

    def set_status(self, service: str, status: AuthStatus):
        self.cache[service] = (status, time.time())
```

## Error Diagnostics

```python
def diagnose_auth_failure(service: str, error: str) -> list[str]:
    """Diagnose common auth failures."""
    suggestions = []

    if "401" in error or "unauthorized" in error.lower():
        suggestions.append("API key may be invalid or expired")
        suggestions.append(f"Verify {service.upper()}_API_KEY is correct")

    if "403" in error or "forbidden" in error.lower():
        suggestions.append("API key may lack required permissions")
        suggestions.append("Check API key scopes in provider dashboard")

    if "network" in error.lower() or "connection" in error.lower():
        suggestions.append("Check network connectivity")
        suggestions.append("Verify proxy settings if applicable")

    ret

Sponsored

Ads related to authentication-patterns and adjacent AI workflows.