fcm-v1-token 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sujeet Kumar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,277 @@
1
+ <div align="center">
2
+
3
+ # 🔥 fcm-v1-token
4
+
5
+ ### Get an FCM v1 OAuth access token from a Firebase service account — and send push notifications — in seconds.
6
+
7
+ A tiny **CLI + Node.js library** that turns a Firebase **service account** key into a short‑lived **OAuth 2.0 access token** for the **Firebase Cloud Messaging (FCM) HTTP v1 API**. The token is **cached for ~1 hour and auto‑refreshed**, so you can send push notifications repeatedly without ever generating it by hand.
8
+
9
+ [![npm version](https://img.shields.io/npm/v/fcm-v1-token.svg)](https://www.npmjs.com/package/fcm-v1-token)
10
+ [![npm downloads](https://img.shields.io/npm/dm/fcm-v1-token.svg)](https://www.npmjs.com/package/fcm-v1-token)
11
+ [![node](https://img.shields.io/node/v/fcm-v1-token.svg)](https://nodejs.org)
12
+ [![license](https://img.shields.io/npm/l/fcm-v1-token.svg)](./LICENSE)
13
+
14
+ </div>
15
+
16
+ ```bash
17
+ npx fcm-v1-token
18
+ ```
19
+
20
+ <div align="center">
21
+ <img src="assets/screenshot-menu.svg" alt="fcm-v1-token interactive CLI menu: get an FCM v1 access token or send a push notification" width="640">
22
+ </div>
23
+
24
+ ---
25
+
26
+ ## Why fcm-v1-token?
27
+
28
+ The legacy FCM server key is **deprecated**. The modern **FCM HTTP v1 API** requires a short‑lived **OAuth 2.0 Bearer token** generated from a **service account**, and that token **expires after 1 hour**. Generating it by hand (sign a JWT, exchange it at `oauth2.googleapis.com/token`, remember to refresh) is fiddly.
29
+
30
+ **fcm-v1-token does it for you** — from the terminal or from code:
31
+
32
+ - 🔑 **Any input** — a service account **file path**, **pasted JSON**, or a credentials **object**
33
+ - 🧠 **Remembers** your service account between runs — set it once, never paste it again
34
+ - 🖥️ **Interactive CLI** — run it and pick what to do (get token / send push)
35
+ - 🔁 **Caches the token ~1 hour and auto‑refreshes** it before expiry
36
+ - 📋 **Copies the token to your clipboard** automatically (and prints it copy‑friendly)
37
+ - 📤 **Sends push** via the FCM v1 API with a one‑line helper
38
+ - 📦 **Zero config**, one dependency (`google-auth-library`), works with `npx`
39
+
40
+ ## Table of contents
41
+
42
+ - [Install](#install)
43
+ - [Quick start (CLI)](#quick-start-cli)
44
+ - [CLI commands](#cli-commands)
45
+ - [Use as a library](#use-as-a-library)
46
+ - [How it works](#how-it-works)
47
+ - [API reference](#api-reference)
48
+ - [Where is my account stored?](#where-is-my-account-stored)
49
+ - [Security](#-security)
50
+ - [FAQ](#faq)
51
+ - [License](#license)
52
+
53
+ ---
54
+
55
+ ## Install
56
+
57
+ Run instantly, no install:
58
+
59
+ ```bash
60
+ npx fcm-v1-token
61
+ ```
62
+
63
+ Or install globally to get the `fcm-v1-token` / `fcm-token` / `fcmt` commands:
64
+
65
+ ```bash
66
+ npm install -g fcm-v1-token
67
+ ```
68
+
69
+ Or add it to a project as a library:
70
+
71
+ ```bash
72
+ npm install fcm-v1-token
73
+ ```
74
+
75
+ ---
76
+
77
+ ## Quick start (CLI)
78
+
79
+ Just run it. The first time, it asks for your service account (file path, pasted JSON, or auto‑detect). After that it **remembers** it.
80
+
81
+ <div align="center">
82
+ <img src="assets/screenshot-paste.svg" alt="First run: choose how to provide the Firebase service account" width="620">
83
+ </div>
84
+
85
+ Pick **Get access token** and you get a color‑coded token that's **already on your clipboard**:
86
+
87
+ <div align="center">
88
+ <img src="assets/screenshot-token.svg" alt="FCM v1 OAuth access token generated and copied to clipboard" width="720">
89
+ </div>
90
+
91
+ Prefer scripting? Print just the token:
92
+
93
+ ```bash
94
+ # Print the raw token using your saved account
95
+ fcm-token token --raw
96
+
97
+ # Capture it into a shell variable
98
+ TOKEN=$(fcm-token token --raw)
99
+
100
+ # Use it directly against the FCM v1 API
101
+ curl -X POST \
102
+ -H "Authorization: Bearer $(fcm-token token --raw)" \
103
+ -H "Content-Type: application/json" \
104
+ -d '{"message":{"token":"<device-token>","notification":{"title":"Hi","body":"Hello"}}}' \
105
+ "https://fcm.googleapis.com/v1/projects/<your-project-id>/messages:send"
106
+ ```
107
+
108
+ ---
109
+
110
+ ## CLI commands
111
+
112
+ ```text
113
+ fcm-token Interactive menu (remembers your last account)
114
+ fcm-token token [source] Print an access token
115
+ fcm-token send [source] Send a test push (interactive prompts)
116
+ fcm-token use <source> Set / replace the saved service account
117
+ fcm-token whoami Show the saved service account
118
+ fcm-token forget Remove the saved service account
119
+ fcm-token --help Show help
120
+ ```
121
+
122
+ `[source]` is **optional** — if omitted, the saved account is used. It can be a **file path** (`./service-account.json`) or **JSON content** (`'{"type":"service_account",...}'`).
123
+
124
+ **Options for `token`:**
125
+
126
+ | Flag | Description |
127
+ | --- | --- |
128
+ | `--raw` | Print only the token — no color, no clipboard (for scripting) |
129
+ | `--json` | Print full info (`token`, `projectId`, `expiresAt`) as JSON |
130
+ | `--no-copy` | Do not copy the token to the clipboard |
131
+
132
+ > Set `NO_COLOR=1` to disable colors. The short alias `fcmt` works everywhere, and `npx fcm-v1-token` runs the same tool without installing.
133
+
134
+ ---
135
+
136
+ ## Use as a library
137
+
138
+ ### Get an access token
139
+
140
+ ```js
141
+ const { getAccessToken } = require('fcm-v1-token');
142
+
143
+ const { token, projectId, expiresAt } = await getAccessToken('./service-account.json');
144
+ // Call getAccessToken() as often as you like — while valid, the same cached
145
+ // token is returned; it auto-refreshes when it expires (~1 hour).
146
+ ```
147
+
148
+ ### Send a push notification (FCM v1)
149
+
150
+ ```js
151
+ const { sendPush } = require('fcm-v1-token');
152
+
153
+ await sendPush('./service-account.json', {
154
+ token: '<device-registration-token>',
155
+ notification: { title: 'Hello', body: 'World' },
156
+ data: { orderId: '123' },
157
+ });
158
+ ```
159
+
160
+ Send to a **topic**:
161
+
162
+ ```js
163
+ await sendPush('./service-account.json', {
164
+ topic: 'news',
165
+ notification: { title: 'Breaking', body: 'Something happened' },
166
+ });
167
+ ```
168
+
169
+ **Validate only** (do not deliver):
170
+
171
+ ```js
172
+ await sendPush(serviceAccount, message, { dryRun: true });
173
+ ```
174
+
175
+ ### Pass content or an object instead of a file path
176
+
177
+ ```js
178
+ // From an environment variable (recommended for servers)
179
+ const sa = JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT);
180
+ await getAccessToken(sa);
181
+
182
+ // Or a pasted JSON string
183
+ await getAccessToken('{"type":"service_account", ...}');
184
+ ```
185
+
186
+ ---
187
+
188
+ ## How it works
189
+
190
+ 1. Reads your service account's `client_email` and `private_key`.
191
+ 2. Signs a **JWT** and exchanges it at `https://oauth2.googleapis.com/token` for an OAuth 2.0 access token, scoped to `https://www.googleapis.com/auth/firebase.messaging`.
192
+ 3. **Caches** the token in memory and **auto‑refreshes** it before the ~1‑hour expiry (powered by `google-auth-library`).
193
+ 4. Uses the token as a `Bearer` credential against `https://fcm.googleapis.com/v1/projects/<project-id>/messages:send`.
194
+
195
+ No secrets ever leave your machine — the token is created and used locally.
196
+
197
+ ---
198
+
199
+ ## API reference
200
+
201
+ | Function | Returns |
202
+ | --- | --- |
203
+ | `getAccessToken(source)` | `{ token, projectId, clientEmail, expiresAt }` |
204
+ | `sendPush(source, message, options?)` | FCM v1 response object |
205
+ | `loadServiceAccount(source)` | validated service account object |
206
+ | `saveLastAccount(sa, source)` | persist an account for later runs → config path |
207
+ | `loadLastAccount()` | saved config, or `null` |
208
+ | `savedSource(saved)` | a usable `source` from a saved config |
209
+ | `forgetLastAccount()` | remove the saved account → `boolean` |
210
+ | `clearCache()` | clear the in‑memory token cache |
211
+
212
+ - **`source`** — a file path (string), pasted JSON content (string), or a credentials object.
213
+ - **`options`** — `{ projectId?, dryRun? }`.
214
+
215
+ TypeScript types are bundled (`src/index.d.ts`).
216
+
217
+ ---
218
+
219
+ ## Where is my account stored?
220
+
221
+ `~/.fcm-v1-token/config.json` (permissions `0600`).
222
+
223
+ - If you passed a **file path**, only the **absolute path** is stored — your key stays in the file.
224
+ - If you **pasted** JSON content, that content is stored in the config file (there is no file to re‑read).
225
+
226
+ Run `fcm-token forget` to remove it.
227
+
228
+ ---
229
+
230
+ ## 🔒 Security
231
+
232
+ A service account **private key grants access to your entire Firebase project**. Treat it like a password:
233
+
234
+ - **Never commit it to git** — add `service-account*.json` to `.gitignore`.
235
+ - **Never paste it into a chat, issue, or screenshot.** If a key is ever exposed, **rotate it immediately** in the [Google Cloud Console → Service Accounts](https://console.cloud.google.com/iam-admin/serviceaccounts) (delete the leaked key, create a new one).
236
+ - On servers, prefer an **environment variable** or a secret manager over a file on disk.
237
+
238
+ ---
239
+
240
+ ## FAQ
241
+
242
+ **How do I get an FCM v1 API access token?**
243
+ Run `npx fcm-v1-token`, choose your service account once, and pick *Get access token* — or in code, `await getAccessToken('./service-account.json')`. The token is a standard Google OAuth 2.0 Bearer token valid for ~1 hour.
244
+
245
+ **How long does an FCM v1 access token last?**
246
+ About **1 hour** (3600 seconds). This tool caches it and refreshes it automatically, so you never hit an expired‑token error while sending push.
247
+
248
+ **How do I send an FCM v1 push notification in Node.js?**
249
+ Use `sendPush(source, message)` — see [Send a push notification](#send-a-push-notification-fcm-v1). It posts to `messages:send` with the right `Authorization: Bearer` header for you.
250
+
251
+ **Do I still need the legacy FCM server key?**
252
+ No. The legacy server key is deprecated. The HTTP v1 API uses OAuth 2.0 tokens from a service account, which is exactly what this tool produces.
253
+
254
+ **Where do I get the service account JSON?**
255
+ Firebase Console → *Project settings* → *Service accounts* → *Generate new private key*. That downloaded JSON is your `source`.
256
+
257
+ **Does it work without installing?**
258
+ Yes — `npx fcm-v1-token` runs it directly. Install globally only if you want the short `fcmt` command always available.
259
+
260
+ **Which platforms are supported for clipboard copy?**
261
+ macOS (`pbcopy`), Windows (`clip`), and Linux (`xclip`). If none is available, the token is still printed — copy it manually.
262
+
263
+ ---
264
+
265
+ ## License
266
+
267
+ [MIT](./LICENSE) © [Sujeet Kumar](https://github.com/TantraIN)
268
+
269
+ ---
270
+
271
+ <div align="center">
272
+ <sub>
273
+
274
+ **Keywords:** FCM v1 access token · Firebase Cloud Messaging HTTP v1 API · OAuth 2.0 bearer token · service account to access token · send FCM push notification Node.js · firebase-admin alternative · FCM token CLI
275
+
276
+ </sub>
277
+ </div>
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "fcm-v1-token",
3
+ "version": "1.0.0",
4
+ "description": "Get an FCM v1 OAuth access token from a Firebase service account (cached ~1h, auto-refreshed) and send push notifications. CLI + library for Firebase Cloud Messaging HTTP v1 API.",
5
+ "main": "src/index.js",
6
+ "types": "src/index.d.ts",
7
+ "bin": {
8
+ "fcm-v1-token": "src/cli.js",
9
+ "fcm-token": "src/cli.js",
10
+ "fcmt": "src/cli.js"
11
+ },
12
+ "scripts": {
13
+ "start": "node src/cli.js",
14
+ "token": "node src/cli.js token",
15
+ "send": "node src/cli.js send"
16
+ },
17
+ "keywords": [
18
+ "fcm",
19
+ "fcm-v1",
20
+ "fcm-http-v1",
21
+ "firebase",
22
+ "firebase-cloud-messaging",
23
+ "push-notification",
24
+ "push-notifications",
25
+ "oauth",
26
+ "oauth2",
27
+ "access-token",
28
+ "bearer-token",
29
+ "service-account",
30
+ "google-auth",
31
+ "messaging",
32
+ "notifications",
33
+ "cli"
34
+ ],
35
+ "author": {
36
+ "name": "Sujeet Kumar",
37
+ "url": "https://github.com/TantraIN"
38
+ },
39
+ "license": "MIT",
40
+ "homepage": "https://github.com/TantraIN/fcm-v1-token#readme",
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "git+https://github.com/TantraIN/fcm-v1-token.git"
44
+ },
45
+ "bugs": {
46
+ "url": "https://github.com/TantraIN/fcm-v1-token/issues"
47
+ },
48
+ "files": [
49
+ "src",
50
+ "README.md",
51
+ "LICENSE"
52
+ ],
53
+ "engines": {
54
+ "node": ">=18"
55
+ },
56
+ "dependencies": {
57
+ "google-auth-library": "^9.14.1"
58
+ }
59
+ }
package/src/cli.js ADDED
@@ -0,0 +1,488 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const readline = require('readline');
7
+ const { spawnSync } = require('child_process');
8
+ const { version: VERSION } = require('../package.json');
9
+ const {
10
+ getAccessToken,
11
+ sendPush,
12
+ loadServiceAccount,
13
+ saveLastAccount,
14
+ loadLastAccount,
15
+ savedSource,
16
+ forgetLastAccount,
17
+ configFile,
18
+ } = require('./index');
19
+
20
+ // ---------------------------------------------------------------------------
21
+ // Colors (auto-disabled when not a TTY or when NO_COLOR is set)
22
+ // ---------------------------------------------------------------------------
23
+
24
+ const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
25
+ const paint = (code) => (s) => (useColor ? `\x1b[${code}m${s}\x1b[0m` : String(s));
26
+ const c = {
27
+ green: paint('32'),
28
+ cyan: paint('36'),
29
+ yellow: paint('33'),
30
+ red: paint('31'),
31
+ gray: paint('90'),
32
+ dim: paint('2'),
33
+ bold: paint('1'),
34
+ bgreen: paint('1;32'),
35
+ bcyan: paint('1;36'),
36
+ };
37
+
38
+ // ---------------------------------------------------------------------------
39
+ // Clipboard (best effort, per platform)
40
+ // ---------------------------------------------------------------------------
41
+
42
+ function copyToClipboard(text) {
43
+ let cmd;
44
+ let args = [];
45
+ if (process.platform === 'darwin') {
46
+ cmd = 'pbcopy';
47
+ } else if (process.platform === 'win32') {
48
+ cmd = 'clip';
49
+ } else {
50
+ cmd = 'xclip';
51
+ args = ['-selection', 'clipboard'];
52
+ }
53
+ try {
54
+ const res = spawnSync(cmd, args, { input: text });
55
+ return res.status === 0;
56
+ } catch (_e) {
57
+ return false;
58
+ }
59
+ }
60
+
61
+ // ---------------------------------------------------------------------------
62
+ // Small prompt helpers
63
+ // ---------------------------------------------------------------------------
64
+
65
+ function withRL(fn) {
66
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
67
+ return Promise.resolve(fn(rl)).finally(() => rl.close());
68
+ }
69
+
70
+ // Ask a question. If `placeholder` is given and we are on a color TTY, show a
71
+ // dim ghost hint after the cursor that disappears as soon as the user types.
72
+ function ask(rl, q, placeholder) {
73
+ return new Promise((resolve) => {
74
+ if (!placeholder || !useColor || !process.stdin.isTTY) {
75
+ rl.question(q, (a) => resolve(a));
76
+ return;
77
+ }
78
+ const onKey = () => {
79
+ // First keypress: wipe the ghost text to the right of the cursor.
80
+ process.stdout.write('\x1b[0K');
81
+ process.stdin.removeListener('keypress', onKey);
82
+ };
83
+ rl.question(q, (a) => {
84
+ process.stdin.removeListener('keypress', onKey);
85
+ resolve(a);
86
+ });
87
+ // Draw ghost hint, then move the cursor back over it so typing overwrites it.
88
+ process.stdout.write(c.dim(placeholder) + `\x1b[${placeholder.length}D`);
89
+ process.stdin.on('keypress', onKey);
90
+ });
91
+ }
92
+
93
+ // Read pasted multi-line JSON. Auto-detects completion once the accumulated
94
+ // text parses as JSON, so the user does not have to type anything after the
95
+ // paste. Typing END on its own line is a manual fallback.
96
+ function readPasted(rl) {
97
+ return new Promise((resolve) => {
98
+ const lines = [];
99
+ console.log('\nPaste the service account JSON now (auto-detected when complete):\n');
100
+ const cleanup = () => rl.removeListener('line', onLine);
101
+ const onLine = (line) => {
102
+ if (line.trim() === 'END') {
103
+ cleanup();
104
+ resolve(lines.join('\n'));
105
+ return;
106
+ }
107
+ lines.push(line);
108
+ const joined = lines.join('\n').trim();
109
+ if (joined.startsWith('{')) {
110
+ try {
111
+ JSON.parse(joined);
112
+ cleanup();
113
+ resolve(joined); // complete JSON object received
114
+ } catch (_e) {
115
+ /* not complete yet — keep reading */
116
+ }
117
+ }
118
+ };
119
+ rl.on('line', onLine);
120
+ });
121
+ }
122
+
123
+ // ---------------------------------------------------------------------------
124
+ // Service account discovery (for auto-detect)
125
+ // ---------------------------------------------------------------------------
126
+
127
+ function looksLikeServiceAccount(file) {
128
+ try {
129
+ const json = JSON.parse(fs.readFileSync(file, 'utf8'));
130
+ return Boolean(json.client_email && json.private_key);
131
+ } catch (_e) {
132
+ return false;
133
+ }
134
+ }
135
+
136
+ function findCandidates(dir, depth = 2) {
137
+ const results = [];
138
+ const IGNORE = new Set(['node_modules', '.git', '.next', 'dist', 'build']);
139
+ function walk(d, level) {
140
+ let entries;
141
+ try {
142
+ entries = fs.readdirSync(d, { withFileTypes: true });
143
+ } catch (_e) {
144
+ return;
145
+ }
146
+ for (const e of entries) {
147
+ if (e.name.startsWith('.') || IGNORE.has(e.name)) continue;
148
+ const full = path.join(d, e.name);
149
+ if (e.isDirectory()) {
150
+ if (level > 0) walk(full, level - 1);
151
+ } else if (e.isFile() && e.name.endsWith('.json') && looksLikeServiceAccount(full)) {
152
+ results.push(full);
153
+ }
154
+ }
155
+ }
156
+ walk(dir, depth);
157
+ return results;
158
+ }
159
+
160
+ // ---------------------------------------------------------------------------
161
+ // Obtain (and remember) a service account interactively
162
+ // ---------------------------------------------------------------------------
163
+
164
+ // Returns { source, saved } where source is a path string or credentials object.
165
+ async function setupServiceAccount(rl) {
166
+ console.log('\nHow do you want to provide the service account?\n');
167
+ console.log(' [1] File path');
168
+ console.log(' [2] Paste JSON content');
169
+ console.log(' [3] Auto-detect from current folder\n');
170
+ const choice = (await ask(rl, c.bcyan('Choose: '), 'enter 1, 2 or 3 and press Enter')).trim();
171
+
172
+ if (choice === '2') {
173
+ const content = await readPasted(rl);
174
+ const sa = loadServiceAccount(content); // validates
175
+ saveLastAccount(sa, { type: 'pasted' });
176
+ console.log(c.green(`\n✓ Saved (${sa.client_email}). It will be remembered next time.`));
177
+ return sa;
178
+ }
179
+
180
+ if (choice === '3') {
181
+ const candidates = findCandidates(process.cwd());
182
+ if (candidates.length === 0) {
183
+ console.log('\nNo service account JSON found in this folder.');
184
+ return setupFromPath(rl);
185
+ }
186
+ console.log('\nService account files found:\n');
187
+ candidates.forEach((f, i) => {
188
+ console.log(` [${i + 1}] ${path.relative(process.cwd(), f)}`);
189
+ });
190
+ const ans = (await ask(rl, c.bcyan('\nChoose a number: '), 'enter a number and press Enter')).trim();
191
+ const idx = parseInt(ans, 10);
192
+ if (!Number.isInteger(idx) || idx < 1 || idx > candidates.length) {
193
+ throw new Error('Invalid choice.');
194
+ }
195
+ return rememberPath(candidates[idx - 1]);
196
+ }
197
+
198
+ // default: file path
199
+ return setupFromPath(rl);
200
+ }
201
+
202
+ async function setupFromPath(rl) {
203
+ const p = (await ask(rl, 'Enter the service account file path: ', 'e.g. ./service-account.json')).trim();
204
+ return rememberPath(p);
205
+ }
206
+
207
+ function rememberPath(p) {
208
+ const abs = path.resolve(p);
209
+ const sa = loadServiceAccount(abs); // validates + throws if bad
210
+ saveLastAccount(sa, { type: 'path', path: abs });
211
+ console.log(`\nSaved (${sa.client_email}). It will be remembered next time.`);
212
+ return abs;
213
+ }
214
+
215
+ // Resolve a usable source: explicit arg > saved config > interactive setup.
216
+ async function resolveSource(rl, pathArg) {
217
+ if (pathArg) {
218
+ // Treat "-" as: read pasted content from stdin is not interactive here,
219
+ // so just handle a normal path/JSON string.
220
+ return rememberFromArg(pathArg);
221
+ }
222
+ const saved = loadLastAccount();
223
+ if (saved) return savedSource(saved);
224
+ return setupServiceAccount(rl);
225
+ }
226
+
227
+ function rememberFromArg(arg) {
228
+ const trimmed = String(arg).trim();
229
+ if (trimmed.startsWith('{')) {
230
+ const sa = loadServiceAccount(trimmed);
231
+ saveLastAccount(sa, { type: 'pasted' });
232
+ return sa;
233
+ }
234
+ return rememberPath(trimmed);
235
+ }
236
+
237
+ // ---------------------------------------------------------------------------
238
+ // Actions
239
+ // ---------------------------------------------------------------------------
240
+
241
+ function fmtExpiry(expiresAt) {
242
+ if (!expiresAt) return 'unknown';
243
+ const mins = Math.round((expiresAt - Date.now()) / 60000);
244
+ return `${new Date(expiresAt).toLocaleString()} (~${mins} min left)`;
245
+ }
246
+
247
+ async function doToken(source, opts = {}) {
248
+ const info = await getAccessToken(source);
249
+ if (opts.json) {
250
+ console.log(JSON.stringify(info, null, 2));
251
+ return;
252
+ }
253
+ if (opts.raw) {
254
+ // Plain, single line — perfect for scripting / piping.
255
+ process.stdout.write(info.token + '\n');
256
+ return;
257
+ }
258
+
259
+ const copied = opts.copy === false ? false : copyToClipboard(info.token);
260
+
261
+ console.log(
262
+ '\n' + c.bgreen('✓ Access token generated') +
263
+ (copied ? c.green(' ✓ copied to clipboard') : '')
264
+ );
265
+ console.log(` ${c.dim('Project')} : ${c.cyan(info.projectId || '(none)')}`);
266
+ console.log(` ${c.dim('Client ')} : ${c.cyan(info.clientEmail)}`);
267
+ console.log(` ${c.dim('Expires')} : ${c.yellow(fmtExpiry(info.expiresAt))}`);
268
+ console.log(c.dim('\n Token (triple-click the line below to select):\n'));
269
+ // Flush-left, on its own line, no wrapping decoration -> easy to copy.
270
+ console.log(c.green(info.token));
271
+ console.log('');
272
+ }
273
+
274
+ async function doSend(rl, source) {
275
+ const deviceToken = (await ask(rl, 'Device (registration) token: ', 'paste the device token')).trim();
276
+ if (!deviceToken) throw new Error('Device token is required.');
277
+ const title = (await ask(rl, 'Title: ', 'e.g. Hello')).trim();
278
+ const body = (await ask(rl, 'Body : ', 'e.g. World')).trim();
279
+
280
+ const res = await sendPush(source, {
281
+ token: deviceToken,
282
+ notification: { title, body },
283
+ });
284
+ console.log(c.bgreen('\n✓ Push sent.') + c.dim(' FCM response:'));
285
+ console.log(' ' + c.cyan(JSON.stringify(res)) + '\n');
286
+ }
287
+
288
+ function showSaved() {
289
+ const saved = loadLastAccount();
290
+ if (!saved) {
291
+ console.log('\nNo service account saved yet.\n');
292
+ return;
293
+ }
294
+ console.log('\nSaved service account:\n');
295
+ console.log(` Client : ${saved.summary.clientEmail}`);
296
+ console.log(` Project : ${saved.summary.projectId || '(none)'}`);
297
+ console.log(` Source : ${saved.source.type}${saved.source.path ? ' — ' + saved.source.path : ''}`);
298
+ console.log(` Saved at : ${saved.savedAt}`);
299
+ console.log(` Config : ${configFile()}\n`);
300
+ }
301
+
302
+ // ---------------------------------------------------------------------------
303
+ // Interactive main menu (default when no command is given)
304
+ // ---------------------------------------------------------------------------
305
+
306
+ async function interactive() {
307
+ printBanner();
308
+ await withRL(async (rl) => {
309
+ let saved = loadLastAccount();
310
+
311
+ if (!saved) {
312
+ console.log(c.yellow('No service account is saved yet. Let’s set one up.'));
313
+ await setupServiceAccount(rl);
314
+ saved = loadLastAccount();
315
+ }
316
+
317
+ // Menu loop
318
+ // eslint-disable-next-line no-constant-condition
319
+ while (true) {
320
+ saved = loadLastAccount();
321
+ const line = c.gray('────────────────────────────────────────');
322
+ console.log('\n' + line);
323
+ console.log(
324
+ c.dim('Using: ') + c.bcyan(saved.summary.clientEmail) +
325
+ (saved.summary.projectId ? c.dim(` (project: ${saved.summary.projectId})`) : '')
326
+ );
327
+ console.log(line);
328
+ console.log(c.bold('What do you want to do?') + '\n');
329
+ console.log(` ${c.green('[1]')} Get access token`);
330
+ console.log(` ${c.green('[2]')} Send a test push`);
331
+ console.log(` ${c.green('[3]')} Change service account`);
332
+ console.log(` ${c.green('[4]')} Forget saved service account`);
333
+ console.log(` ${c.green('[5]')} Exit\n`);
334
+
335
+ const choice = (await ask(rl, c.bcyan('Choose: '), 'enter 1-5 and press Enter')).trim();
336
+
337
+ try {
338
+ if (choice === '1') {
339
+ await doToken(savedSource(saved));
340
+ } else if (choice === '2') {
341
+ await doSend(rl, savedSource(saved));
342
+ } else if (choice === '3') {
343
+ await setupServiceAccount(rl);
344
+ } else if (choice === '4') {
345
+ forgetLastAccount();
346
+ console.log(c.yellow('\nForgotten. Setting up a new one.'));
347
+ await setupServiceAccount(rl);
348
+ } else if (choice === '5' || choice.toLowerCase() === 'exit' || choice === '') {
349
+ console.log(c.dim('\nBye.\n'));
350
+ return;
351
+ } else {
352
+ console.log(c.red('\nInvalid choice.'));
353
+ }
354
+ } catch (err) {
355
+ // Keep the menu alive on a failed action (bad key, network, etc.).
356
+ console.error(c.red(`\nError: ${err.message}`));
357
+ }
358
+ }
359
+ });
360
+ }
361
+
362
+ // ---------------------------------------------------------------------------
363
+ // Help + arg parsing
364
+ // ---------------------------------------------------------------------------
365
+
366
+ // A compact, colorful header shown at startup and in help.
367
+ function printBanner() {
368
+ const rule = c.gray('──────────────────────────────────────────────────────');
369
+ console.log('');
370
+ console.log(' ' + c.bcyan('🔥 fcm-v1-token') + c.dim(` v${VERSION}`));
371
+ console.log(' ' + c.dim('Firebase service account ') + c.gray('→') +
372
+ c.dim(' FCM v1 OAuth token & push'));
373
+ console.log(' ' + rule);
374
+ console.log(' ' + c.dim('Turns a service account key into a 1-hour access token'));
375
+ console.log(' ' + c.dim('for the FCM v1 API — cached & auto-refreshed — and can'));
376
+ console.log(' ' + c.dim('send push notifications. Remembers your account.'));
377
+ console.log('');
378
+ }
379
+
380
+ function printHelp() {
381
+ printBanner();
382
+ console.log(` Commands: fcm-v1-token | fcm-token | fcmt (via npx: npx fcm-v1-token)
383
+
384
+ Run with no arguments for an interactive menu. Your service account
385
+ (path or pasted content) is remembered between runs.
386
+
387
+ Usage:
388
+ fcm-token Interactive menu (remembers last account)
389
+ fcm-token token [source] Print an access token
390
+ fcm-token send [source] Send a test push (interactive prompts)
391
+ fcm-token use <source> Set / replace the saved service account
392
+ fcm-token whoami Show the saved service account
393
+ fcm-token forget Remove the saved service account
394
+ fcm-token --help This help
395
+
396
+ [source] is optional. If omitted, the saved account is used. It can be:
397
+ - a file path e.g. ./service-account.json
398
+ - JSON content e.g. '{"type":"service_account",...}'
399
+
400
+ Options (for "token"):
401
+ --json Print full info (token, projectId, expiry) as JSON
402
+ --raw Print only the token (for scripting)
403
+ --no-copy Do not copy the token to the clipboard
404
+
405
+ Examples:
406
+ npx fcm-v1-token # menu, remembers your file
407
+ fcm-token use ./service-account.json # remember this file
408
+ fcm-token token --raw # print token using saved account
409
+ TOKEN=$(fcm-token token --raw)
410
+ fcm-token send # push using saved account
411
+ `);
412
+ }
413
+
414
+ async function main() {
415
+ const argv = process.argv.slice(2);
416
+
417
+ if (argv.includes('--help') || argv.includes('-h')) {
418
+ printHelp();
419
+ return;
420
+ }
421
+
422
+ const opts = {
423
+ json: argv.includes('--json'),
424
+ raw: argv.includes('--raw'),
425
+ copy: !argv.includes('--no-copy'),
426
+ };
427
+ const positional = argv.filter((a) => !a.startsWith('--'));
428
+
429
+ const COMMANDS = new Set(['token', 'send', 'use', 'whoami', 'forget']);
430
+ let command;
431
+ let sourceArg;
432
+ if (positional.length && COMMANDS.has(positional[0])) {
433
+ command = positional[0];
434
+ sourceArg = positional[1];
435
+ } else if (positional.length) {
436
+ // First positional is a source -> default to token.
437
+ command = 'token';
438
+ sourceArg = positional[0];
439
+ }
440
+
441
+ // No command at all -> interactive menu.
442
+ if (!command) {
443
+ await interactive();
444
+ return;
445
+ }
446
+
447
+ if (command === 'whoami') {
448
+ showSaved();
449
+ return;
450
+ }
451
+
452
+ if (command === 'forget') {
453
+ const ok = forgetLastAccount();
454
+ console.log(ok ? '\nSaved service account removed.\n' : '\nNothing was saved.\n');
455
+ return;
456
+ }
457
+
458
+ if (command === 'use') {
459
+ if (!sourceArg) {
460
+ // Interactive setup if no source given.
461
+ await withRL((rl) => setupServiceAccount(rl));
462
+ } else {
463
+ rememberFromArg(sourceArg);
464
+ const saved = loadLastAccount();
465
+ console.log(`\nSaved (${saved.summary.clientEmail}).\n`);
466
+ }
467
+ return;
468
+ }
469
+
470
+ if (command === 'token') {
471
+ const source = await withRL((rl) => resolveSource(rl, sourceArg));
472
+ await doToken(source, opts);
473
+ return;
474
+ }
475
+
476
+ if (command === 'send') {
477
+ await withRL(async (rl) => {
478
+ const source = await resolveSource(rl, sourceArg);
479
+ await doSend(rl, source);
480
+ });
481
+ return;
482
+ }
483
+ }
484
+
485
+ main().catch((err) => {
486
+ console.error(c.red(`\nError: ${err.message}\n`));
487
+ process.exit(1);
488
+ });
package/src/index.d.ts ADDED
@@ -0,0 +1,75 @@
1
+ export interface ServiceAccount {
2
+ client_email: string;
3
+ private_key: string;
4
+ project_id?: string;
5
+ [key: string]: unknown;
6
+ }
7
+
8
+ export interface AccessTokenInfo {
9
+ token: string;
10
+ projectId: string | null;
11
+ clientEmail: string;
12
+ /** epoch ms, or null if the library did not expose an expiry */
13
+ expiresAt: number | null;
14
+ }
15
+
16
+ export interface SendOptions {
17
+ /** Override the service account's project_id */
18
+ projectId?: string;
19
+ /** true => FCM validate_only (does not deliver, only validates) */
20
+ dryRun?: boolean;
21
+ }
22
+
23
+ export interface SavedSource {
24
+ type: 'path' | 'pasted';
25
+ path?: string | null;
26
+ }
27
+
28
+ export interface SavedConfig {
29
+ savedAt: string;
30
+ source: SavedSource;
31
+ summary: { clientEmail: string; projectId: string | null };
32
+ serviceAccount?: ServiceAccount;
33
+ }
34
+
35
+ /** `source` can be a file path, pasted JSON content, or a credentials object. */
36
+ export type Source = string | ServiceAccount;
37
+
38
+ /** Load + validate a service account from a path, JSON content, or object. */
39
+ export function loadServiceAccount(source: Source): ServiceAccount;
40
+
41
+ /** Get an OAuth2 access token. Cached (~1h) + auto-refresh. */
42
+ export function getAccessToken(source: Source): Promise<AccessTokenInfo>;
43
+
44
+ /**
45
+ * Send an FCM v1 message.
46
+ * @param message FCM v1 "message" object (token/topic/condition + notification/data)
47
+ */
48
+ export function sendPush(
49
+ source: Source,
50
+ message: Record<string, unknown>,
51
+ options?: SendOptions
52
+ ): Promise<Record<string, unknown>>;
53
+
54
+ /** Remember a service account for later runs. */
55
+ export function saveLastAccount(
56
+ sa: ServiceAccount,
57
+ source: SavedSource
58
+ ): string;
59
+
60
+ /** Load the saved config, or null if none. */
61
+ export function loadLastAccount(): SavedConfig | null;
62
+
63
+ /** Turn a saved config into a `source` usable by getAccessToken/sendPush. */
64
+ export function savedSource(saved: SavedConfig): Source;
65
+
66
+ /** Forget the saved service account. Returns true if something was removed. */
67
+ export function forgetLastAccount(): boolean;
68
+
69
+ /** Path to the saved config file. */
70
+ export function configFile(): string;
71
+
72
+ /** Clear the in-memory token client cache. */
73
+ export function clearCache(): void;
74
+
75
+ export const FCM_SCOPE: string;
package/src/index.js ADDED
@@ -0,0 +1,259 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+ const { JWT } = require('google-auth-library');
7
+
8
+ const FCM_SCOPE = 'https://www.googleapis.com/auth/firebase.messaging';
9
+
10
+ // Ek hi service account ke liye baar-baar naya JWT client mat banao.
11
+ // google-auth-library ka JWT client token ko internally cache karta hai
12
+ // (~1 hour) aur expire hone par khud refresh kar leta hai.
13
+ // Cache key = client_email.
14
+ const clientCache = new Map();
15
+
16
+ /**
17
+ * Load + validate a service account from a file path, a pasted JSON string,
18
+ * or a credentials object.
19
+ * @param {string|object} source - file path, JSON content, or credentials object.
20
+ * @returns {object} parsed service account
21
+ */
22
+ function loadServiceAccount(source) {
23
+ if (source && typeof source === 'object') {
24
+ assertValid(source, '<object>');
25
+ return source;
26
+ }
27
+ if (typeof source !== 'string' || source.trim() === '') {
28
+ throw new Error('Provide a service account file path, JSON content, or object.');
29
+ }
30
+
31
+ const trimmed = source.trim();
32
+
33
+ // Pasted JSON content (starts with "{") instead of a file path.
34
+ if (trimmed.startsWith('{')) {
35
+ let json;
36
+ try {
37
+ json = JSON.parse(trimmed);
38
+ } catch (_e) {
39
+ throw new Error('Invalid service account JSON content.');
40
+ }
41
+ assertValid(json, '<pasted content>');
42
+ return json;
43
+ }
44
+
45
+ const abs = path.resolve(source);
46
+ let raw;
47
+ try {
48
+ raw = fs.readFileSync(abs, 'utf8');
49
+ } catch (_e) {
50
+ throw new Error(`Service account file not found: ${abs}`);
51
+ }
52
+
53
+ let json;
54
+ try {
55
+ json = JSON.parse(raw);
56
+ } catch (_e) {
57
+ throw new Error(`Service account file is not valid JSON: ${abs}`);
58
+ }
59
+
60
+ assertValid(json, abs);
61
+ return json;
62
+ }
63
+
64
+ function assertValid(json, where) {
65
+ if (!json.client_email || !json.private_key) {
66
+ throw new Error(
67
+ `Not a valid service account (missing client_email/private_key): ${where}`
68
+ );
69
+ }
70
+ }
71
+
72
+ function getClient(sa) {
73
+ let client = clientCache.get(sa.client_email);
74
+ if (!client) {
75
+ client = new JWT({
76
+ email: sa.client_email,
77
+ key: sa.private_key,
78
+ scopes: [FCM_SCOPE],
79
+ });
80
+ clientCache.set(sa.client_email, client);
81
+ }
82
+ return client;
83
+ }
84
+
85
+ /**
86
+ * Get an OAuth2 access token from a service account.
87
+ * The token is cached (~1 hour) and auto-refreshed before it expires,
88
+ * so it is safe to call this repeatedly (e.g. before every push).
89
+ *
90
+ * @param {string|object} source - file path, JSON content, or credentials object
91
+ * @returns {Promise<{token: string, projectId: string, clientEmail: string, expiresAt: number|null}>}
92
+ */
93
+ async function getAccessToken(source) {
94
+ const sa = loadServiceAccount(source);
95
+ const client = getClient(sa);
96
+ const { token } = await client.getAccessToken();
97
+ if (!token) {
98
+ throw new Error('Failed to obtain access token (Google returned an empty token).');
99
+ }
100
+ return {
101
+ token,
102
+ projectId: sa.project_id || null,
103
+ clientEmail: sa.client_email,
104
+ expiresAt: (client.credentials && client.credentials.expiry_date) || null,
105
+ };
106
+ }
107
+
108
+ /**
109
+ * FCM v1 API se ek message bhejo.
110
+ *
111
+ * @param {string|object} source - service account file path YA object
112
+ * @param {object} message - FCM v1 "message" object, e.g.
113
+ * { token: '<device-token>', notification: { title, body }, data: {...} }
114
+ * @param {object} [options]
115
+ * @param {string} [options.projectId] - override; default service account ka project_id
116
+ * @param {boolean} [options.dryRun] - true => validate_only (bhejta nahi, sirf check)
117
+ * @returns {Promise<object>} FCM ka response
118
+ */
119
+ async function sendPush(source, message, options = {}) {
120
+ if (!message || typeof message !== 'object') {
121
+ throw new Error('Provide an FCM "message" object (e.g. { token, notification }).');
122
+ }
123
+
124
+ const { token, projectId } = await getAccessToken(source);
125
+ const project = options.projectId || projectId;
126
+ if (!project) {
127
+ throw new Error('No project_id found — pass options.projectId if it is not in the service account.');
128
+ }
129
+
130
+ const res = await fetch(
131
+ `https://fcm.googleapis.com/v1/projects/${project}/messages:send`,
132
+ {
133
+ method: 'POST',
134
+ headers: {
135
+ Authorization: `Bearer ${token}`,
136
+ 'Content-Type': 'application/json',
137
+ },
138
+ body: JSON.stringify({ message, validate_only: !!options.dryRun }),
139
+ }
140
+ );
141
+
142
+ let data = {};
143
+ try {
144
+ data = await res.json();
145
+ } catch (_e) {
146
+ /* empty body */
147
+ }
148
+
149
+ if (!res.ok) {
150
+ const err = new Error(
151
+ `FCM send failed (HTTP ${res.status}): ${JSON.stringify(data)}`
152
+ );
153
+ err.status = res.status;
154
+ err.response = data;
155
+ throw err;
156
+ }
157
+ return data;
158
+ }
159
+
160
+ /** Clear the in-memory token client cache (testing / key rotation). */
161
+ function clearCache() {
162
+ clientCache.clear();
163
+ }
164
+
165
+ // ---------------------------------------------------------------------------
166
+ // Persistence: remember the last-used service account across CLI runs.
167
+ // Stored under ~/.fcm-v1-token/config.json with 0600 permissions.
168
+ // For a file path we store only the absolute path (key stays in the file).
169
+ // For pasted content we store the full JSON (there is no file to re-read).
170
+ // ---------------------------------------------------------------------------
171
+
172
+ function configDir() {
173
+ return path.join(os.homedir(), '.fcm-v1-token');
174
+ }
175
+
176
+ function configFile() {
177
+ return path.join(configDir(), 'config.json');
178
+ }
179
+
180
+ /**
181
+ * Remember a service account for later runs.
182
+ * @param {object} sa - validated service account object
183
+ * @param {{type: 'path'|'pasted', path?: string}} source
184
+ * @returns {string} config file path
185
+ */
186
+ function saveLastAccount(sa, source) {
187
+ fs.mkdirSync(configDir(), { recursive: true, mode: 0o700 });
188
+ const payload = {
189
+ savedAt: new Date().toISOString(),
190
+ source: { type: source.type, path: source.path || null },
191
+ summary: {
192
+ clientEmail: sa.client_email,
193
+ projectId: sa.project_id || null,
194
+ },
195
+ };
196
+ // Only persist the key material when it was pasted (no file to fall back to).
197
+ if (source.type === 'pasted') payload.serviceAccount = sa;
198
+
199
+ const file = configFile();
200
+ fs.writeFileSync(file, JSON.stringify(payload, null, 2), { mode: 0o600 });
201
+ try {
202
+ fs.chmodSync(file, 0o600);
203
+ } catch (_e) {
204
+ /* best effort */
205
+ }
206
+ return file;
207
+ }
208
+
209
+ /** Load the saved config, or null if none. */
210
+ function loadLastAccount() {
211
+ let parsed;
212
+ try {
213
+ parsed = JSON.parse(fs.readFileSync(configFile(), 'utf8'));
214
+ } catch (_e) {
215
+ return null;
216
+ }
217
+ return parsed && parsed.source ? parsed : null;
218
+ }
219
+
220
+ /**
221
+ * Turn a saved config into a `source` usable by getAccessToken/sendPush.
222
+ * @returns {string|object} path string or credentials object
223
+ */
224
+ function savedSource(saved) {
225
+ if (saved.source.type === 'pasted') {
226
+ if (!saved.serviceAccount) {
227
+ throw new Error('Saved service account content is missing; set it again.');
228
+ }
229
+ return saved.serviceAccount;
230
+ }
231
+ if (!saved.source.path) {
232
+ throw new Error('Saved service account path is missing; set it again.');
233
+ }
234
+ return saved.source.path;
235
+ }
236
+
237
+ /** Forget the saved service account. Returns true if something was removed. */
238
+ function forgetLastAccount() {
239
+ try {
240
+ fs.unlinkSync(configFile());
241
+ return true;
242
+ } catch (_e) {
243
+ return false;
244
+ }
245
+ }
246
+
247
+ module.exports = {
248
+ getAccessToken,
249
+ sendPush,
250
+ loadServiceAccount,
251
+ clearCache,
252
+ // persistence
253
+ saveLastAccount,
254
+ loadLastAccount,
255
+ savedSource,
256
+ forgetLastAccount,
257
+ configFile,
258
+ FCM_SCOPE,
259
+ };