CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-rails--ujs

Ruby on Rails unobtrusive scripting adapter that enables modern JavaScript behaviors through HTML5 data attributes

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

csrf-protection.mddocs/

CSRF Protection

Cross-Site Request Forgery protection system that automatically handles CSRF tokens for all requests and forms, ensuring secure communication with Rails applications.

Capabilities

CSRF Token Retrieval

Gets the current CSRF token from the page's meta tags.

/**
 * Get up-to-date Cross-Site Request Forgery token from meta tag
 * @returns Current CSRF token or null if not found
 */
function csrfToken(): string | null;

Usage Examples:

// Get current CSRF token
const token = Rails.csrfToken();
if (token) {
  console.log("CSRF Token:", token);
}

// Use in custom AJAX request
fetch("/api/data", {
  method: "POST",
  headers: {
    "X-CSRF-Token": Rails.csrfToken(),
    "Content-Type": "application/json"
  },
  body: JSON.stringify({ data: "value" })
});

CSRF Parameter Name

Gets the CSRF parameter name that should be used in forms.

/**
 * Get URL param name that must contain the CSRF token
 * @returns CSRF parameter name or null if not found
 */
function csrfParam(): string | null;

Usage Examples:

// Get CSRF parameter name (typically "authenticity_token")
const paramName = Rails.csrfParam();
console.log("CSRF param name:", paramName);

// Build form data with CSRF token
const formData = new FormData();
formData.append(Rails.csrfParam(), Rails.csrfToken());
formData.append("title", "My Post");

Automatic CSRF Protection

Automatically adds CSRF token to XMLHttpRequest headers for same-origin requests.

/**
 * Add CSRF token to XHR request headers
 * @param xhr - XMLHttpRequest instance to add protection to
 */
function CSRFProtection(xhr: XMLHttpRequest): void;

Usage Examples:

// Manual XHR request with CSRF protection
const xhr = new XMLHttpRequest();
xhr.open("POST", "/api/data");
Rails.CSRFProtection(xhr); // Adds X-CSRF-Token header
xhr.send(data);

// This is automatically called by Rails.ajax() for same-origin requests
Rails.ajax({
  type: "POST",
  url: "/api/data",
  data: formData
  // CSRFProtection is automatically applied
});

CSRF Token Refresh

Updates all form CSRF tokens on the page with the current token value, useful for long-lived pages.

/**
 * Update all form CSRF tokens with current token from meta tag
 * Finds all forms with CSRF token inputs and updates their values
 */
function refreshCSRFTokens(): void;

Usage Examples:

// Refresh all CSRF tokens on the page
Rails.refreshCSRFTokens();

// This is automatically called on DOMContentLoaded
// but can be called manually for dynamic content
document.addEventListener("DOMContentLoaded", Rails.refreshCSRFTokens);

// Refresh tokens after AJAX navigation
fetch("/new-page")
  .then(response => response.text())
  .then(html => {
    document.body.innerHTML = html;
    Rails.refreshCSRFTokens(); // Update tokens in new content
  });

HTML Integration

CSRF protection relies on meta tags in the HTML head:

<head>
  <meta name="csrf-param" content="authenticity_token" />
  <meta name="csrf-token" content="abc123xyz789..." />
</head>

Form Integration

Rails automatically generates hidden CSRF fields in forms:

<form action="/posts" method="post">
  <input type="hidden" name="authenticity_token" value="abc123xyz789..." />
  <input type="text" name="title" />
  <input type="submit" value="Create" />
</form>

AJAX Integration

All AJAX requests made through Rails.ajax() automatically include CSRF protection:

  • Same-origin requests get X-CSRF-Token header
  • Cross-origin requests skip CSRF protection
  • X-Requested-With: XMLHttpRequest header identifies AJAX requests

jQuery Integration

When jQuery is present, Rails UJS automatically adds CSRF protection to all jQuery AJAX requests:

// Automatically protected when jQuery is available
$.ajax({
  type: "POST",
  url: "/api/data",
  data: { title: "My Post" }
  // X-CSRF-Token header automatically added
});

CSP Nonce Support

Gets Content Security Policy nonce for inline scripts, supporting secure script execution.

/**
 * Get Content Security Policy nonce for inline scripts
 * @returns Current CSP nonce or null if not found
 */
function cspNonce(): string | null;

/**
 * Load and cache CSP nonce from meta tag
 * @returns CSP nonce value or null if not found
 */
function loadCSPNonce(): string | null;

Usage Examples:

// Get CSP nonce for inline scripts
const nonce = Rails.cspNonce();
if (nonce) {
  const script = document.createElement("script");
  script.setAttribute("nonce", nonce);
  script.text = "console.log('Secure script');";
  document.head.appendChild(script);
}

// Load nonce from meta tag (called automatically on DOMContentLoaded)
Rails.loadCSPNonce();

HTML Integration:

<head>
  <meta name="csp-nonce" content="abc123nonce456" />
</head>

Security Considerations

  • CSRF tokens are only added to same-origin requests
  • Cross-origin requests must handle CSRF protection separately
  • Tokens should be refreshed periodically for long-lived pages
  • Meta tags must be present in HTML for token retrieval to work
  • CSP nonces are used for secure inline script execution when processing JavaScript responses

Token Lifecycle

  1. Rails server generates CSRF token and includes in meta tags
  2. Rails UJS reads token from meta tags on page load
  3. Token is automatically added to all same-origin AJAX requests
  4. Form hidden fields are updated with current token value
  5. Server validates token on protected requests

Install with Tessl CLI

npx tessl i tessl/npm-rails--ujs

docs

ajax-remote.md

csrf-protection.md

dom-utilities.md

element-state.md

event-system.md

feature-handlers.md

form-handling.md

index.md

tile.json