implement-api-authentication

implement-api-authentication is a cursor rule for Cursor from PaulJPhilp/EffectPatterns. It costs 1,065 tokens per session, scanned A, original, MIT.

A TypeScript rule for protecting an API with middleware that checks authentication tokens before a request reaches its handler.

In plain words
What is it for?
Use it to validate tokens, identify the current user, and return unauthorized or forbidden responses from an HTTP service.
Why use it?
It stops unauthenticated requests early and provides a place to distinguish users who lack permission for a required role.

Cursor rule for Cursor

Written for Cursor: a Cursor rule (.mdc).

Good fit Use it to validate tokens, identify the current user, and return unauthorized or forbidden responses from an HTTP service.

Compare 6 cursor rules from other repositories ↓
Install with agentmods
npx agentmods add rules/pauljphilp/effectpatterns/implement-api-authentication
Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

Clone the repo
git clone --depth 1 https://github.com/PaulJPhilp/EffectPatterns

Made for: Cursor.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for implement-api-authentication

README.md
[![agentmods](https://agentmods.dev/badge/rules/pauljphilp/effectpatterns/implement-api-authentication/github.svg)](https://agentmods.dev/rules/pauljphilp/effectpatterns/implement-api-authentication)
Your own site
<a href="https://agentmods.dev/rules/pauljphilp/effectpatterns/implement-api-authentication"><img src="https://agentmods.dev/badge/rules/pauljphilp/effectpatterns/implement-api-authentication/github.svg" alt="Measured on agentmods" height="20"></a>

Or the 80×15 button, for a site that already has a row of RSS and ATOM ones. Only the verdict fits; the numbers stay here.

agentmods 80×15 button for implement-api-authentication

Your own site · 80×15
<a href="https://agentmods.dev/rules/pauljphilp/effectpatterns/implement-api-authentication"><img src="https://agentmods.dev/badge/rules/pauljphilp/effectpatterns/implement-api-authentication.svg" alt="Reviewed on agentmods" width="80" height="20"></a>
Per session 1,065 This file is loaded in full into every session.
When invoked 1,065 The same file — it is already loaded in full.
Security scan A 0 findings. A grade says what 26 rules found in the file — not that it is safe.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.01065 $0.01065
Opus 5.5 $0.00426 $0.00426
Sonnet 5.5 $0.00213 $0.00213
Haiku 4.5 $0.00106 $0.00106

Measured 2mo ago against content hash 147dae28a5d9, method: parsed. Prices are Anthropic first-party input rates as of 2026-10-07, from the pricing page.

Security

Grade A, and why

implement-api-authentication scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 2mo ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

content/published/rules/cursor/implement-api-authentication.mdc · 185 lines

How it starts

The opening of the file, as written. The whole thing — 185 lines — stays where its author put it; the contents beside it link to each section on GitHub.

description: Use middleware to validate authentication tokens before handling requests. globs: "**/*.ts" alwaysApply: true

Implement API Authentication

Rule: Use middleware to validate authentication tokens before handling requests.

Example

import { Effect, Context, Layer, Data } from "effect"
import { HttpServer, HttpServerRequest, HttpServerResponse } from "@effect/platform"

// ============================================
// 1. Define authentication types
// ============================================

interface User {
  readonly id: string
  readonly email: string
  readonly roles: ReadonlyArray<string>
}

class AuthenticatedUser extends Context.Tag("AuthenticatedUser")<
  AuthenticatedUser,
  User
>() {}

class UnauthorizedError extends Data.TaggedError("UnauthorizedError")<{
  readonly reason: string
}> {}

class ForbiddenError extends Data.TaggedError("ForbiddenError")<{
  readonly requiredRole: string
}> {}

// ============================================
// 2. JWT validation service
// ============================================

interface JwtService {
  readonly verify: (token: string) => Effect.Effect<User, UnauthorizedError>
}

class Jwt extends Context.Tag("Jwt")<Jwt, JwtService>() {}

const JwtLive = Layer.succeed(Jwt, {
  verify: (token) =>
    Effect.gen(function* () {
      // In production: use a real JWT library
      if (!token || token === "invalid") {
        return yield* Effect.fail(new UnauthorizedError({ 
          reason: "Invalid or expired token" 
        }))
      }

      // Decode token (simplified)
      if (token.startsWith("user-")) {
        return {
          id: token.replace("user-", ""),
          email: "[email protected]",
          roles: ["user"],
        }
      }

      if (token.startsWith("admin-")) {
        return {
          id: token.replace("admin-", ""),
          email: "[email protected]",
          roles: ["user", "admin"],
        }
      }

      return yield* Effect.fail(new UnauthorizedError({ 
        reason: "Malformed token" 
      }))
    }),
})

// ============================================
// 3. Authentication middleware
// ============================================

const extractBearerToken = (header: string | undefined): string | null => {
  if (!header?.startsWith("Bearer ")) return null
  return header.slice(7)
}

const authenticate = <A, E, R>(
  handler: Effect.Effect<A, E, R | AuthenticatedUser>
): Effect.Effect<A, E | UnauthorizedError, R | Jwt | HttpServerRequest.HttpServerRequest> =>
  Effect.gen(function* () {
    const request = yield* HttpServerRequest.HttpServerRequest
    const jwt = yield* Jwt

    const authHeader = request.headers["authorization"]
    const token = extractBearerToken(authHeader)

    if (!token) {
      return yield* Effect.fail(new UnauthorizedError({ 
        reason: "Missing Authorization header" 
      }))
    }

    const user = yield* jwt.verify(token)

    return yield* handler.pipe(
      Effect.provideService(AuthenticatedUser, user)
    )
  })

// ============================================
// 4. Role-based authorization
// ============================================

const requireRole = (role: string) =>
  <A, E, R>(handler: Effect.Effect<A, E, R | AuthenticatedUser>) =>
    Effect.gen(function* () {
      const user = yield* AuthenticatedUser

      if (!user.roles.includes(role)) {
        return yield* Effect.fail(new ForbiddenError({ requiredRole: role }))
      }

      return yield* handler
    })

// ============================================
// 5. Protected routes
// ============================================

const getProfile = authenticate(
  Effect.gen(function* () {
    const user = yield* AuthenticatedUser
    return HttpServerResponse.json({
      id: user.id,
      email: user.email,
      roles: user.roles,
    })
  })
)

const adminOnly = authenticate(
  requireRole("admin")(
    Effect.gen(function* () {
      const user = yield* AuthenticatedUser
      return HttpServerResponse.json({
        message: `Welcome admin ${user.email}`,
        users: ["user1", "user2", "user3"],
      })
    })
  )
)

// ============================================
// 6. Error handling
// ============================================

const handleAuthErrors = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
  effect.pipe(
    Effect.catchTag("UnauthorizedError", (e) =>
      Effect.succeed(
        HttpServerResponse.json({ error: e.reason }, { status: 401 })
      )
    ),
    Effect.catchTag("ForbiddenError", (e) =>
      Effect.succeed(
        HttpServerResponse.json(
          { error: `Requires role: ${e.requiredRole}` },
          { status: 403 }
        )
      )
    )
  )

Read the full file on GitHub · 185 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 2mo ago First seen · 185 lines · 1,065 tokens per session scan A 147dae28a5d9

Subscribe to this mod's changes

implement-api-authentication is a cursor rule published in the GitHub repository PaulJPhilp/EffectPatterns (807 stars, last pushed 5mo ago), licensed MIT. It adds 1,065 tokens to every session, about $0.0043 per session on Opus 5.5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-09-03.

Related

implement-api-authentication compared with cursor rules from other repositories

implement-api-authentication next to 6 cursor rules from other repositories
ModTypeStarsLast pushLicenceScanTokensWorks with
implement-api-authenticationPaulJPhilp/EffectPatternsCursor rule8075mo agoMITA1,065Cursor
workflowWebDevPeterGriffin/The-VibeCode-BibleCursor rule4226d agononeA0Cursor
activitiesWebDevPeterGriffin/The-VibeCode-BibleCursor rule4226d agononeA0Cursor
go-api-development-general-rulesWebDevPeterGriffin/The-VibeCode-BibleCursor rule4226d agononeA0Cursor
backend-general-expertWebDevPeterGriffin/The-VibeCode-BibleCursor rule4226d agononeA349Cursor
service-class-conventionsWebDevPeterGriffin/The-VibeCode-BibleCursor rule4226d agononeA172Cursor
repository-class-conventionsWebDevPeterGriffin/The-VibeCode-BibleCursor rule4226d agononeA149Cursor