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

directus-extension-sso-helper

v1.1.0

Published

Helper for SSO cross-domain

Readme

Directus SSO Helper Extension

Giới thiệu

Extension này giúp tích hợp đăng nhập Single Sign-On (SSO) qua Google OAuth cho hệ thống Directus, hỗ trợ xác thực người dùng từ frontend qua backend một cách an toàn, đơn giản và đa môi trường (dev, staging, production).

Vấn đề thường gặp: Khi backend (Directus) và frontend (token server/web app) nằm ở các domain khác nhau, cookie xác thực (như refresh token) không thể chia sẻ cross-domain do chính sách bảo mật trình duyệt. Nếu dùng SSO mặc định của Directus, frontend sẽ không nhận được session/cookie hợp lệ, gây lỗi xác thực hoặc không thể duy trì đăng nhập.

Lý do sử dụng

  • Cho phép frontend (token server) xác thực người dùng Google qua Directus, nhận JWT token hợp lệ.
  • Đơn giản hóa luồng xác thực SSO đa môi trường.
  • Tách biệt logic xác thực OAuth khỏi frontend, tăng bảo mật.
  • Giải quyết triệt để vấn đề không share được cookie cross-domain giữa backend và frontend.

Cách tích hợp

1. Cài đặt extension vào Directus

  • npm i directus-extension-sso-helper

2. Cấu hình ENV cho Directus

Thêm các biến môi trường sau vào file .env của Directus:

# URL public của hệ thống (bắt buộc)
PUBLIC_URL=https://your-directus-domain.com

# Tên cookie lưu refresh token (bắt buộc)
REFRESH_TOKEN_COOKIE_NAME=your_refresh_token_cookie

# Mỗi môi trường cần 2 biến encode/redirect URL, ví dụ cho DEV:
SSO_DEV_ENCODE_URL=https://your-token-server.com/api/token
SSO_DEV_REDIRECT_URL=https://your-frontend.com/sso-callback

# Tương tự cho STAGING, PROD...
SSO_STAGING_ENCODE_URL=...
SSO_STAGING_REDIRECT_URL=...

3. Backend (Directus)

  • Extension sẽ tự động tạo 3 endpoint:
    • /sso-auth/:provider/:env (bắt đầu luồng SSO)
    • /sso-callback/:env (xử lý callback qua middleware chain)
    • /token-exchange (FE gửi JWT exchange để nhận thông tin hợp lệ)

4. Frontend

  • Khi user bấm "Login with Google", gọi endpoint /sso-auth/{provider}/{env} trên Directus.
  • Sau khi xác thực thành công, Directus redirect về /sso-callback/{env} với 2 case:
    • type=exchange: FE nhận JWT exchange và gọi POST /token-exchange để lấy thông tin hợp lệ
    • mặc định: FE nhận token trực tiếp để sử dụng theo hệ thống của bạn

4.1 Frontend code example (Exchange flow - khuyến nghị)

const express = require('express');
const jwt = require('jsonwebtoken');

const app = express();
const PORT = 8080;
const SECRET = 'your-very-secret-key'; // In production, use env vars

app.use(express.json());

// 1) FE nhận redirect từ Directus: /sso-callback?token=...&type=exchange
app.get('/sso-callback', async (req, res) => {
    const { token, type } = req.query;
    if (!token) return res.status(400).json({ error: 'Token is required' });

    // 2) Nếu type=exchange, gọi Directus POST /token-exchange để hợp thức hóa
    if (type === 'exchange') {
        try {
            const resp = await fetch(`${process.env.DIRECTUS_URL}/token-exchange`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ token })
            });
            const data = await resp.json();
            if (!resp.ok) return res.status(resp.status).json(data);

            // Lưu refresh/access token theo nhu cầu của bạn
            // Ví dụ: res.cookie('access_token', data.accessToken)
            return res.json({ success: true, data });
        } catch (e) {
            return res.status(500).json({ error: 'Token exchange failed' });
        }
    }

    // 3) Type mặc định: dùng token trực tiếp (tùy hệ thống của bạn)
    return res.json({ success: true, token });
});

app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
});
sequenceDiagram
    participant User
    participant Frontend
    participant Directus
    participant Google OAuth

    User->>Frontend: Click "Login with Google"
    Frontend ->>Directus: GET /sso-auth/google/{env}
    Directus->>Google OAuth: Redirect to Google OAuth
    Google OAuth->>User: Google login page
    User->>Google OAuth: Enter credentials
    Google OAuth->>Directus: Redirect with auth code
    Directus->>Directus: Process OAuth callback
    Directus->>Frontend: POST /api/token with refresh_token
    Frontend ->>Directus: Return JWT token
    Directus->>Frontend: Redirect with JWT token
    Frontend ->>User: Authenticated session

5. Các trường hợp lỗi xác định từ reason

[FE SSO Callback]/sso-callback?reason=${reason}&error=true

  • ?error=true: Có lỗi
  • &reason=INVALID_CREDENTIALS: Lỗi khác provider (email/pass # GOOGLE # Apple)
  • &reason=AUTH_SERVER_ERROR: Không lấy được refresh token từ Cookie
  • &reason=AUTH_SERVICE_ERROR: Lỗi khi gọi FE endpoint encode token
  • &reason=SERVICE_UNAVAILABLE: Lỗi từ Directus khi dịch vụ SSO lỗi

Changelog

  • 1.0.9: Thêm support cho other provider with param provider
  • 1.1.0: Thêm endpoint token-exchange và hỗ trợ SSO type "exchange" với JWT bảo mật

Tính năng mới: Token Exchange

1. Endpoint Token Exchange

Endpoint /token-exchange xác thực JWT exchange và trả về thông tin hợp lệ:

POST /token-exchange

{
  "token": "jwt_token_here"
}

Response:

{
  "success": true,
  "refreshToken": "refresh_token_from_cookie"
}

2. SSO Type "Exchange"

Khi cấu hình SSO_{ENV}_TYPE=exchange, sso-callback sẽ:

  • Không gọi backend bên ngoài
  • Sử dụng context.env['secret'] có sẵn để sign JWT
  • Tạo JWT token với security code và refresh token
  • Token có thời hạn 1 phút
  • Redirect về frontend với type=exchange

Cấu hình ENV bổ sung (Directus .env):

# Security Code (bắt buộc cho token exchange)
SECURITY_CODE=your-security-code

# Allowed Roles (tùy chọn, mặc định: admin,user)
ALLOWED_ROLES=admin,user,moderator

# SECRET dùng để ký/verify JWT nội bộ (Directus đã có sẵn biến SECRET)
SECRET=your-directus-secret

# Base
PUBLIC_URL=https://your-directus-domain.com
REFRESH_TOKEN_COOKIE_NAME=your_refresh_token_cookie

# Config theo từng env (ví dụ DEV)
SSO_DEV_TYPE=exchange            # hoặc default
SSO_DEV_ENCODE_URL=https://your-token-server.com/api/token
SSO_DEV_REDIRECT_URL=https://your-frontend.com/sso-callback

3. Middleware Architecture

Extension sử dụng kiến trúc middleware modular để xử lý các trường hợp khác nhau:

Thứ tự middleware:

  1. ssoValidationMiddleware: Kiểm tra và thiết lập SSO context
  2. reasonMiddleware: Xử lý trường hợp có lỗi (reason parameter)
  3. exchangeMiddleware: Xử lý SSO type "exchange" với JWT bảo mật
  4. defaultMiddleware: Xử lý SSO type mặc định

Cấu trúc file:

src/
├── utils/
│   ├── sso-jwt.ts                # Shared types and JWT utilities
│   ├── sso-validation-middleware.ts  # SSO validation
│   └── async-handler.ts          # Async error handler
└── ep-sso-callback/
    ├── index.ts                  # Main callback endpoint
    └── middleware/
        ├── reason-middleware.ts       # Error handling
        ├── exchange-middleware.ts     # Exchange type handling
        └── default-middleware.ts      # Default type handling

4. Bảo mật

  • JWT token có thời hạn 1 phút
  • Kiểm tra security code
  • Validation role permissions
  • Error handling chi tiết