pinme-auth

pinme-auth

Popular

Use when a PinMe project (Worker TypeScript) needs to integrate user authentication — creating email/password users, verifying id_tokens, querying user info, or listing users via Identity Platform auth proxy APIs.

3.7Kstars
276forks
Updated 9/12/2026
SKILL.md
read-only
name
pinme-auth
description

Use when a PinMe project (Worker TypeScript) needs to integrate user authentication — creating email/password users, verifying id_tokens, querying user info, or listing users via Identity Platform auth proxy APIs.

PinMe Worker Auth API Integration

Guides how to call PinMe platform's Identity Platform auth proxy APIs in a PinMe Worker (TypeScript).

Environment Variables

// backend/src/worker.ts
export interface Env {
  DB: D1Database;
  API_KEY: string;       // Project API Key — used for authenticating all auth API calls
  PROJECT_NAME: string;  // Project name — required alongside API Key for all auth endpoints
  BASE_URL?: string;     // Optional, defaults to https://pinme.cloud
}

API_KEY and PROJECT_NAME are required credentials for all auth endpoints and must both be provided.


Authentication Method (Common to All Endpoints)

Parameter Passing Method Required Description
X-API-Key Request Header Yes Project API Key
project_name Query Parameter Yes Must match the same project associated with X-API-Key

The server first validates whether these two fields correspond to the same project, retrieves tenant_id from the project configuration, and forwards the request to Identity Platform.


Common Errors

Scenario HTTP data.error
Missing X-API-Key 401 X-API-Key header is required
Missing project_name 400 project_name is required
API Key and project mismatch 401 Invalid API key or project name
Auth service tenant not configured for project 400 Auth service not configured for this project

Common TypeScript Types

type ApiEnvelope<T> = {
  code: number   // 200 = success, other = failure
  msg: string    // "ok" | "fail" | "invalid param"
  data: T
}

type ApiErrorData = { error?: string }

type UserInfo = {
  uid: string
  email: string
  display_name: string
  photo_url?: string
  disabled: boolean
  email_verified: boolean
}

API 1: Create User

Endpoint: POST {BASE_URL}/api/v1/auth/create_user?project_name={project_name}

Used exclusively for email/password registration. On success, the user is created and a verification email is sent. On failure, changes are automatically rolled back to prevent orphaned accounts.

Upon successful creation, the user remains in an unverified state by default. verify_token will pass validation only after the user clicks the email verification link.

Request Body

{ "email": "alice@example.com", "password": "Test@12345678", "display_name": "Alice" }
Field Type Required
email string Yes
password string Yes
display_name string No

Errors

Scenario HTTP data.error
Missing email/password 400 email and password are required
Upstream creation failure 502 Failed to create user
Failed to send verification email 500 Failed to send verification email. Please try again.

TypeScript Example

async function createAuthUser(
  env: Env,
  payload: { email: string; password: string; display_name?: string }
): Promise<{ user?: UserInfo; error?: string }> {
  const baseUrl = env.BASE_URL ?? 'https://pinme.cloud';
  const resp = await fetch(
    `${baseUrl}/api/v1/auth/create_user?project_name=${encodeURIComponent(env.PROJECT_NAME)}`,
    {
      method: 'POST',
      headers: { 'X-API-Key': env.API_KEY, 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    }
  );
  const result = await resp.json() as ApiEnvelope<UserInfo | ApiErrorData>;
  if (!resp.ok || result.code !== 200) {
    return { error: (result.data as ApiErrorData)?.error ?? result.msg };
  }
  return { user: result.data as UserInfo };
}

API 2: Verify id_token

Endpoint: POST {BASE_URL}/api/v1/auth/verify_token?project_name={project_name}

Verifies the id_token obtained after frontend login (applies to both email/password and Google login).

Note: If the token is valid but the email is not verified, 403 is returned instead of 401.

Request Body

{ "id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6..." }

Successful Response data

type VerifyTokenData = {
  uid: string
  email?: string
  tenant_id: string
  claims: Record<string, unknown>
}

Errors

Scenario HTTP data.error
Missing id_token 400 id_token is required
Token invalid or expired 401 Invalid or expired token
Email not verified 403 Email not verified. Please check your inbox and verify your email address.

TypeScript Example

async function verifyAuthToken(
  env: Env,
  idToken: string
): Promise<{ uid?: string; email?: string; error?: string; emailNotVerified?: boolean }> {
  const baseUrl = env.BASE_URL ?? 'https://pinme.cloud';
  const resp = await fetch(
    `${baseUrl}/api/v1/auth/verify_token?project_name=${encodeURIComponent(env.PROJECT_NAME)}`,
    {
      method: 'POST',
      headers: { 'X-API-Key': env.API_KEY, 'Content-Type': 'application/json' },
      body: JSON.stringify({ id_token: idToken }),
    }
  );
  const result = await resp.json() as ApiEnvelope<VerifyTokenData | ApiErrorData>;
  if (!resp.ok || result.code !== 200) {
    const error = (result.data as ApiErrorData)?.error ?? result.msg;
    return { error, emailNotVerified: resp.status === 403 };
  }
  const data = result.data as VerifyTokenData;
  return { uid: data.uid, email: data.email };
}

API 3: Query Single User

Endpoint: GET {BASE_URL}/api/v1/auth/user?project_name={project_name}&uid={uid}

Errors

Scenario HTTP data.error
Missing uid 400 uid is required
User does not exist 404 User not found
Upstream query failure 502 Failed to get user

TypeScript Example

async function getAuthUser(env: Env, uid: string): Promise<{ user?: UserInfo; error?: string }> {
  const baseUrl = env.BASE_URL ?? 'https://pinme.cloud';
  const resp = await fetch(
    `${baseUrl}/api/v1/auth/user?project_name=${encodeURIComponent(env.PROJECT_NAME)}&uid=${encodeURIComponent(uid)}`,
    { method: 'GET', headers: { 'X-API-Key': env.API_KEY } }
  );
  const result = await resp.json() as ApiEnvelope<UserInfo | ApiErrorData>;
  if (!resp.ok || result.code !== 200) {
    return { error: (result.data as ApiErrorData)?.error ?? result.msg };
  }
  return { user: result.data as UserInfo };
}

API 4: List Users (Paginated)

Endpoint: GET {BASE_URL}/api/v1/auth/list_users?project_name={project_name}

Defaults to max_results=100, maximum 1000. Iterate pages using next_page_token.

Query Parameters

Parameter Required Description
project_name Yes Project name
page_token No Pagination cursor
max_results No Page size, 1–1000

TypeScript Example

async function listAuthUsers(
  env: Env,
  options: { pageToken?: string; maxResults?: number } = {}
): Promise<{ users?: UserInfo[]; nextPageToken?: string; error?: string }> {
  const baseUrl = env.BASE_URL ?? 'https://pinme.cloud';
  const url = new URL('/api/v1/auth/list_users', baseUrl);
  url.searchParams.set('project_name', env.PROJECT_NAME);
  if (options.pageToken) url.searchParams.set('page_token', options.pageToken);
  if (options.maxResults) url.searchParams.set('max_results', String(options.maxResults));

  const resp = await fetch(url.toString(), { method: 'GET', headers: { 'X-API-Key': env.API_KEY } });
  const result = await resp.json() as ApiEnvelope<{ users: UserInfo[]; next_page_token?: string } | ApiErrorData>;
  if (!resp.ok || result.code !== 200) {
    return { error: (result.data as ApiErrorData)?.error ?? result.msg };
  }
  const data = result.data as { users: UserInfo[]; next_page_token?: string };
  return { users: data.users, nextPageToken: data.next_page_token };
}

// Example: Batch iterate all users
async function* iterAllUsers(env: Env) {
  let pageToken: string | undefined;
  do {
    const { users, nextPageToken, error } = await listAuthUsers(env, { pageToken, maxResults: 1000 });
    if (error) throw new Error(error);
    for (const user of users ?? []) yield user;
    pageToken = nextPageToken;
  } while (pageToken);
}

Frontend Integration (Firebase Auth)

The create_worker response includes public_client_config, which the frontend uses to initialize the Firebase Auth SDK.

Distinguishing the Two api_key Fields

Field Purpose Safe for Browser Exposure
data.api_key Project API Key used for calling proxy APIs in this document No, Worker/server side only
data.public_client_config.auth_api_key Firebase Web API Key used for initializing frontend login SDK Yes

public_client_config Fields Description

Field Frontend Purpose
public_client_config.auth_api_key initializeApp({ apiKey })
public_client_config.auth_domain initializeApp({ authDomain })
public_client_config.auth_project_id initializeApp({ projectId })
public_client_config.tenant_id auth.tenantId = config.tenant_id (Required; missing this causes token tenant misassignment)

Frontend TypeScript Example

import { initializeApp } from 'firebase/app'
import {
  type Auth,
  getAuth,
  GoogleAuthProvider,
  signInWithEmailAndPassword,
  signInWithPopup,
} from 'firebase/auth'

type PublicClientConfig = {
  tenant_id: string
  auth_api_key: string
  auth_domain: string
  auth_project_id: string
}

export function createProjectAuth(config: PublicClientConfig): Auth {
  const app = initializeApp({
    apiKey: config.auth_api_key,
    authDomain: config.auth_domain,
    projectId: config.auth_project_id,
  })
  const auth = getAuth(app)
  auth.tenantId = config.tenant_id  // Required: Ensures tokens belong to the correct tenant
  return auth
}

// Email and password login, returns id_token
export async function loginWithEmail(auth: Auth, email: string, password: string): Promise<string> {
  const credential = await signInWithEmailAndPassword(auth, email, password)
  return credential.user.getIdToken()
}

// Google login, returns id_token
export async function loginWithGoogle(auth: Auth): Promise<string> {
  const credential = await signInWithPopup(auth, new GoogleAuthProvider())
  return credential.user.getIdToken()
}

// Usage Example
// pinme create automatically writes public_client_config to frontend/src/utils/config.ts
import { public_client_config } from '../utils/config'

const auth = createProjectAuth(public_client_config)
const idToken = await loginWithGoogle(auth)
// Then send idToken to your Worker, which invokes verify_token

The frontend is only responsible for user sign-in and retrieving id_token. Do not expose the project api_key on the frontend. verify_token must be proxied via your Worker or backend service.
frontend/src/utils/config.ts is generated automatically by pinme create and does not need to be created manually.


Typical Calling Flows

Email/Password Registration Flow:

  1. create_user → Creates user and sends verification email
  2. User clicks the email link to complete verification
  3. Frontend signs in and gets id_token
  4. verify_token → Validates token and returns uid
  5. Optional: Call getAuthUser to retrieve full user details when needed

Google Login Flow:

  1. Frontend completes Google Sign-In and gets id_token
  2. verify_token → Validates token (no need to call create_user)

Common Pitfalls

Mistake Correct Approach
Passing only X-API-Key while omitting project_name Every request must include both the X-API-Key header and project_name query parameter
Treating verify_token 403 response as invalid token 403 means email unverified (prompt user to check inbox); 401 indicates invalid/expired token
Assuming email is verified right after successful create_user Creation success only means the verification email was sent; user must click the link to verify
Fetching only the first page in list_users When next_page_token is present, continue querying until it is empty
Checking success using only resp.ok Check both resp.ok && result.code === 200