npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

moc-oauth-client

v3.0.9

Published

OAuth client for Ministry of Commerce, Cambodia

Readme

moc-oauth-client

TypeScript SDK for integrating backend applications with the Ministry of Commerce Identity OAuth API.

Use this package from your server, API, or backend-for-frontend. Do not use it directly in browser code because it requires your OAuth client secret.

What It Does

  • Creates an Identity login redirect URL
  • Exchanges an authorization code for provider-issued tokens
  • Validates an access token by looking up the user profile
  • Refreshes provider-issued tokens
  • Revokes a refresh token on logout

Installation

npm install moc-oauth-client

Node.js 18 or newer is required.

Configuration

You can configure the SDK with environment variables:

BASE_URL=https://identity-api-dev.moc.gov.kh
CLIENT_ID=your_client_id
CLIENT_SECRET=your_client_secret
REDIRECT_URI=https://your-app.example.com/callback
import { MOCOAuthClient } from "moc-oauth-client";

const oauth = new MOCOAuthClient();

Or pass configuration directly:

const oauth = new MOCOAuthClient({
  baseUrl: "https://identity-api-dev.moc.gov.kh",
  clientId: "your_client_id",
  clientSecret: "your_client_secret",
  redirectUri: "https://your-app.example.com/callback",
  timeoutMs: 10000,
});

OAuth Flow

  1. Generates an OAuth state value and PKCE codeVerifier.
  2. Derives an S256 codeChallenge from the verifier.
  3. Stores state and codeVerifier in its own secure session/cookie storage.
  4. Call getLoginToken({ state, codeChallenge }).
  5. Redirect the user to result.data.redirectUri.
  6. The user signs in with MOC Identity.
  7. MOC Identity redirects back to your REDIRECT_URI with code and state.
  8. Verify the returned state.
  9. Call validateAuthorizationCode({ code, codeVerifier }).
  10. Store or session-manage the returned provider accessToken and refreshToken.
  11. Use lookupUserProfile(accessToken) in protected API routes to validate the token.
  12. Use refreshToken(refreshToken) when the access token expires.
  13. Use logout(refreshToken) to revoke the session.

Response Shape

All methods return a result object. API failures are returned in error; they are not thrown.

type ApiResponse<T> =
  | {
      status: number;
      success: true;
      message?: string;
      data: T;
      error: null;
    }
  | {
      status?: number;
      success: false;
      data: null;
      error: {
        code: string;
        message: string;
        status?: number;
      };
    };

Recommended handling:

const result = await oauth.lookupUserProfile(accessToken);

if (!result.success) {
  console.error(result.error.code, result.error.message);
  return;
}

console.log(result.data.email);

Methods

getLoginToken()

Creates a login URL for the configured OAuth client.

Example:

const result = await oauth.getLoginToken({
  state,
  codeChallenge,
  codeChallengeMethod: "S256",
});

if (result.success) {
  response.redirect(result.data.redirectUri);
}

Success data:

{
  "redirectUri": "https://identity.example.com/login?loginToken=..."
}

validateAuthorizationCode({ code, codeVerifier })

Exchanges the authorization code for provider-issued tokens.

Example:

const result = await oauth.validateAuthorizationCode({
  code,
  codeVerifier,
});

if (!result.success || !result.data.isValid || !result.data.payload) {
  throw new Error(result.error?.message ?? "Invalid authorization code");
}

const { accessToken, refreshToken, email } = result.data.payload;

Success data:

{
  "isValid": true,
  "payload": {
    "id": 1,
    "email": "[email protected]",
    "username": "[email protected]",
    "position": "រដ្ឋលេខាធិការ",
    "isActive": true,
    "domain": "your-app.example.com",
    "accessToken": "...",
    "refreshToken": "..."
  }
}

lookupUserProfile(accessToken)

Validates an access token and returns the current user profile.

Example:

const result = await oauth.lookupUserProfile(accessToken);

if (!result.success) {
  throw new Error(result.error.message);
}

return result.data;

Success data:

{
  "id": 1,
  "email": "[email protected]",
  "username": "[email protected]",
  "position": "រដ្ឋលេខាធិការ",
  "isActive": true
}

refreshToken(refreshToken)

Exchanges a valid provider refresh token for a new token pair.

Example:

const result = await oauth.refreshToken(refreshToken);

if (result.success) {
  session.accessToken = result.data.accessToken;
  session.refreshToken = result.data.refreshToken;
}

logout(refreshToken)

Revokes a provider refresh token.

Example:

await oauth.logout(refreshToken);

Express Middleware Example

import type { Request, Response, NextFunction } from "express";
import { MOCOAuthClient } from "moc-oauth-client";

const oauth = new MOCOAuthClient();

export async function requireMocUser(
  req: Request,
  res: Response,
  next: NextFunction,
) {
  const authorization = req.headers.authorization;
  const accessToken = authorization?.startsWith("Bearer ")
    ? authorization.slice(7)
    : null;

  if (!accessToken) {
    return res.status(401).json({ message: "Missing bearer token" });
  }

  const result = await oauth.lookupUserProfile(accessToken);

  if (!result.success || !result.data.isActive) {
    return res.status(result.status ?? 401).json({ error: result.error });
  }

  req.user = result.data;
  next();
}

Compatibility Aliases

Older integrations can still use:

  • authorizeClient() as an alias of getLoginToken()
  • getCurrentUser() as an alias of lookupUserProfile()

Prefer the newer method names in new code.

Security Notes

  • Keep CLIENT_SECRET only on the server.
  • Store refresh tokens securely.
  • Do not generate replacement tokens in your client API unless you have a specific token-exchange design.
  • Validate access tokens through lookupUserProfile() or a trusted local validation strategy that matches the Identity provider.
  • Use HTTPS for redirect URIs in production.