Skip to content

About

Unofficial Facebook Messenger client library for Node.js, written in TypeScript. Typed API, secure local session storage, reliable reconnects, zero runtime dependencies. For personal use with your own account. Work in progress.

Topics

Resources

Security policy

Stars

6 stars

Watchers

0 watching

Forks

Repository files navigation

fca-unofficial

CI License: MIT Node.js ≥ 24 TypeScript Dependencies: 0

An unofficial Facebook Messenger client library for Node.js, written in TypeScript.

It is built for personal use with your own account: long-running local tools that read your messages and process them on your own machine. It has a typed API, keeps your session safe on disk, reconnects reliably, and sends nothing anywhere except to Facebook.

Warning

Early development. Receiving messages, edits, unsends, reactions and typing indicators is implemented and tested against a local simulation of Facebook's gateway, but has not yet been verified against live Messenger. See Project status and Roadmap.

Contents

Highlights

  • Reliable connection lifecycle. A single supervised reconnect loop with exponential backoff, jitter and cancellation, and an explicit state machine. It is tested so that repeated "connection lost" signals produce exactly one reconnect.
  • No missed messages. Sync cursors are saved with your session. After a dropped connection or a restart, messages that arrived in the meantime are delivered and marked recovered; periodic reconciliation guards against silent stalls, and duplicates are suppressed.
  • Safe sessions. Cookies are imported locally from your own browser. Sessions are stored in atomic, checksummed files with optional AES-256-GCM encryption. Corruption is detected, never silently ignored.
  • No secrets in logs. Every logger, including one you supply, passes through a redactor. Errors carry safe diagnostic details only.
  • Typed, stable API. Your code works with typed events and domain objects, never raw protocol payloads.
  • Minimal footprint. Zero runtime dependencies, ESM, strict TypeScript.
  • No login automation. No password login, no 2FA handling, no checkpoint or captcha bypassing. You log in with your normal browser.

Project status

The same information is available at runtime as FEATURE_STATUS.

Feature Status
Session import and validation (local) stable
Session storage (atomic, checksummed, optional encryption) stable
Connection lifecycle and reconnect supervision stable
Session validation with Facebook, checkpoint detection experimental
Receiving messages in real time, with catch-up after gaps experimental
Edits, unsends, reactions, typing indicators experimental
Attachment details (photos, files, links) planned
Thread list, message history, user profiles planned
End-to-end encrypted chats not supported (under evaluation)
Sending messages not supported (planned after read-only)

Stable means implemented, tested and independent of Facebook's protocol. Experimental means implemented and tested, but not yet verified against live Facebook. Protocol behaviour is tested against synthetic data modelled on documented sources, never against recorded traffic.

Important

Personal one-to-one chats on Messenger are end-to-end encrypted by default. Their content travels over a separate protocol that this library does not support. See protocol status §9.

Requirements

  • Node.js 24 or later
  • A Facebook account you own, logged in through a normal browser

Installation

The library is installed from GitHub. It is not published to npm; the npm package named fca-unofficial belongs to someone else and is unrelated to this project.

git clone https://github.com/yohannzapata/fca-unofficial.git
cd fca-unofficial
npm ci
npm run build

Quick start

1. Export your cookies. Log in to https://www.facebook.com in your browser and export the facebook.com cookies to a file, either as the Cookie request header or as a JSON cookie export. The required cookies are c_user, xs and datr, and sb and fr are recommended. Keep the file outside the project folder. See docs/sessions.md.

2. Import them into a local, optionally encrypted session file. Setting FCA_USER_AGENT to your browser's user agent (run navigator.userAgent in its DevTools console) keeps requests consistent with that browser.

FCA_SESSION_PASSPHRASE="a long passphrase" FCA_USER_AGENT="…" node examples/basic/import-session.ts ~/Downloads/cookies.txt

Then delete the exported cookie file.

Tip

In PowerShell, set variables first, for example $env:FCA_SESSION_PASSPHRASE = "…", then run node examples/basic/import-session.ts "$HOME\Downloads\cookies.txt".

3. Check the session. The read-only probe loads facebook.com/messages once and prints a report that contains no secrets:

FCA_SESSION_PASSPHRASE="a long passphrase" node tools/probe.ts

4. Use the client:

import {
  MessengerClient,
  FileSessionStore,
  createPassphraseCodec,
  createConsoleLogger,
} from "fca-unofficial";

const client = new MessengerClient({
  session: new FileSessionStore({
    path: ".session/messenger.json",
    codec: createPassphraseCodec({ passphrase: process.env.FCA_SESSION_PASSPHRASE! }),
  }),
  logger: createConsoleLogger({ level: "info" }), // silent by default
});

client.on("message", (message) => {
  const tag = message.recovered ? " (while offline)" : "";
  console.log(`[${message.threadId}] ${message.senderId}: ${message.text ?? "(no text)"}${tag}`);
});
client.on("stateChange", ({ from, to, reason }) => console.log(`${from} -> ${to}`, reason ?? ""));
client.on("error", (error) => console.error(error.code, error.message));
process.once("SIGINT", () => void client.destroy());

await client.connect(); // resolves once connected and synced; reconnects automatically

The first run on a newly imported session records the current inbox position and reports nothing old. From then on, messages that arrive while your program is not running are delivered when it next connects. A complete version is in examples/basic/connect.ts.

API overview

API Purpose
new MessengerClient({ session, logger?, reconnect?, userAgent? }) Creates a client for one account
client.connect() / disconnect() / destroy() Lifecycle. disconnect() and destroy() are idempotent
client.on(event, listener) Subscribe to an event (below). Returns an unsubscribe function
client.state, client.health() Current connection state and a local health snapshot
sessionFromCookies(input) Validates exported cookies locally and builds a session
FileSessionStore, MemorySessionStore Session storage. Implement SessionStore for your own backend
createPassphraseCodec(), createAesGcmCodec() Optional encryption at rest for FileSessionStore
probeSession({ session }) Read-only session check with a secret-free report
MessengerError and subclasses Typed errors with stable code values. See docs/errors.md
Event Payload
message Message: id, threadId, senderId, text, timestamp, isFromMe, mentions, replyTo, …
messageEdit { messageId, threadId, text, editCount }
messageDelete { messageId, threadId, reason: "unsent" | "removed" }
reactionAdd / reactionRemove { messageId, threadId, actorId, reaction, isFromMe }
typing { threadId, userId, isTyping }
ready, stateChange, error Connection lifecycle and failures

Message-level events carry recovered: true when they were delivered by catch-up synchronization rather than pushed live. IDs are strings, because Messenger IDs exceed JavaScript's safe integer range. Delivery is at-least-once across restarts, so if you store messages, key them on message.id.

Documentation

Document Contents
Sessions Exporting cookies, storing sessions, encryption, expiry
Errors Error codes and what to do about them
Security Threat model, network destinations, secret handling, dependencies
Architecture Layers, lifecycle, event pipeline, session subsystem
Protocol status What is known about Messenger's protocol, with evidence levels
Existing projects Review of other Messenger client libraries
Architecture options Design alternatives considered

Roadmap

  • Real-time message receiving. Facebook's current web gateway (DGW) and Lightspeed sync, with gap filling after reconnects and restarts.
  • Message events. Edits, unsends, reactions and typing indicators, with duplicate suppression.
  • Live verification. Confirm the protocol behaviour against live Messenger and move the experimental features to stable.
  • Read API. Thread list, message history, user profiles and attachment details.
  • Long-running reliability. Soak and fault-injection testing.
  • Later. End-to-end encrypted chats (under evaluation), sending messages, and an optional compatibility layer for code written against older FCA-style APIs.

Security and privacy

  • The library contacts only Facebook's own hosts. There is no telemetry, analytics, update check or third-party service.
  • Session files never leave your machine unless you move them yourself.
  • Report vulnerabilities privately. See SECURITY.md.

Caution

Your session cookies work like your password. Never share them, commit them, or paste them into issues.

Disclaimer

This project is not affiliated with, endorsed by, or supported by Meta Platforms, Inc. Meta provides no official API for personal Messenger accounts, and its Terms of Service restrict automated access. Using this library may lead to restrictions on your account, and it may stop working whenever Facebook changes its web client. Use it at your own risk, and only with an account you own.

This is an independent implementation. It shares no code with other packages or forks named fca-unofficial.

Development

npm run check   # type check, lint, format check and tests
npm test        # tests only
npm run build   # compile to dist/

Dependency install scripts are disabled through .npmrc. CI runs the full check on Linux and Windows.

License

MIT © Yohann Joachim Zapata

About

Unofficial Facebook Messenger client library for Node.js, written in TypeScript. Typed API, secure local session storage, reliable reconnects, zero runtime dependencies. For personal use with your own account. Work in progress.

Topics

Resources

Security policy

Stars

6 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages