Skip to content

Add a JSON response helper and a CSRF token convention for AJAX requests #528

Open

Description

@caseysoftware

Current state

  • No JSON convention. Core has no shared way to return JSON. Modules use suppressHeaders=1 and hand-roll their output, while the gzip and w2p_add_form_tokens() output buffers stay active around it.
  • The token only reaches forms. The CSRF token ($AppUI->getFormToken()) is injected into POST <form> tags by the w2p_add_form_tokens() output filter. JavaScript has no supported way to read it.
  • The gate is narrow. The CSRF gate in index.php (~line 234) only covers dosql posts and a=do_* / domodsql actions. It reads __nonce from POST or GET only.
  • Failures answer in HTML. A failed check calls setMsg() and redirect(), which sends an HTML redirect to a script.
  • Expired sessions answer in HTML. An expired session returns the HTML login page with status 200. A script can't tell it apart from success.
  • Good news: the token is per session, not per request (checkFormToken() compares against $AppUI->__nonce), so rapid AJAX calls won't trip over a rotating token.

Intended solution

Expose the token to scripts

  • The theme header adds <meta name="w2p-nonce" content="...">.
  • js/base.js gets a small w2p.request(url, {method, json}) helper. It sends:
    • the token as an X-W2P-Nonce header;
    • Accept: application/json;
    • a JSON body.
  • It returns the parsed envelope (below).

Accept the header at the gate

  • The index.php gate also reads $_SERVER['HTTP_X_W2P_NONCE'].
  • Optional: extend the gate to every POST/PUT/PATCH/DELETE request, not just do_*. This needs an audit of existing non-do_ POST pages first.

Answer JSON callers in JSON

When the request asks for JSON (Accept: application/json):

  • a failed CSRF check returns 403 JSON instead of redirecting;
  • an unauthenticated request returns 401 JSON instead of the login page.

w2p_Output_JSON helper

  • send($data, $status = 200) and error($status, $code, $message, $fields = []):
    • discard all open output buffers first (gzip, form-token filter);
    • set Content-Type: application/json; charset=utf-8, Cache-Control: no-store and X-Content-Type-Options: nosniff;
    • encode with JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_INVALID_UTF8_SUBSTITUTE (the base schema is latin1, so stray bytes must not break a response);
    • exit.
  • input() decodes a JSON request body from php://input.

One envelope

  • Success: {"ok": true, "data": ...}
  • Failure: {"ok": false, "error": {"code": "stale_version", "message": "...", "fields": {...}}}
  • Status codes:
    • 400 validation;
    • 401 not logged in;
    • 403 permission or CSRF;
    • 404 not found;
    • 409 version conflict.
  • Messages go through $AppUI->_() for translation.

Endpoint convention

?m=<module>&a=do_<name>_json&suppressHeaders=1. The do_ prefix keeps the CSRF gate in force automatically.

Acceptance

  • A w2p.request() POST to a do_*_json action with the header passes the CSRF gate.
  • The same request without the header gets a 403 JSON error.
  • An expired session gets 401 JSON.
  • Responses are valid JSON with no gzip or token-filter artifacts.

Context

The Cards module (caseysoftware/modules-cards) needs this for drag-and-drop saves on its board.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions