firevault 0.1.1-beta.2 → 0.1.1-beta.3

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/README.md CHANGED
@@ -49,6 +49,10 @@ firevault init
49
49
 
50
50
  `firevault init` asks for your Firebase project ID, service account path, output directory, and collections. It also checks Git state before writing files and appends safety entries to `.gitignore`.
51
51
 
52
+ During setup, Firevault looks for likely Firebase project IDs in local files such as `.env.local`, `.env.development`, `firebase.json`, and common Firebase config files. Detection is best-effort and transparent: if Firevault finds candidates, it shows where they came from and lets you accept one or enter a value manually.
53
+
54
+ Firevault also looks for likely local service account files such as `serviceAccountKey.json`, `service-account.json`, `firebase-service-account.json`, and `credentials/firebase.json`. It never prints private key contents. If you select a service account path, Firevault adds that path to `.gitignore`.
55
+
52
56
  After you enter a project ID, Firevault prints the direct Firebase Console URL for that project's Admin SDK service account page:
53
57
 
54
58
  ```txt
@@ -63,6 +67,8 @@ Download the JSON key and save it as:
63
67
 
64
68
  Firevault does not create service accounts, open a browser, run `gcloud`, or authenticate against Firebase during setup.
65
69
 
70
+ If the selected service account file already exists, Firevault can optionally connect to Firestore and list top-level collections so you can choose which ones to back up. If the file is missing or Firebase access fails, init continues and you can enter collections manually.
71
+
66
72
  Generated `firevault.config.json`:
67
73
 
68
74
  ```json
@@ -3,6 +3,9 @@ import { createInterface } from "node:readline/promises";
3
3
  import { stdin as input, stdout as output } from "node:process";
4
4
  import { appendFileSync, existsSync, readFileSync, writeFileSync, } from "node:fs";
5
5
  import { GitError, hasWorkingTreeChanges, initGitRepository, isInsideGitRepository, } from "../git/git.js";
6
+ import { detectFirebaseProjectCandidates, uniqueProjectIds, } from "../init/detectFirebaseProject.js";
7
+ import { detectServiceAccountPaths } from "../init/detectServiceAccount.js";
8
+ import { listFirestoreCollections } from "../init/listCollections.js";
6
9
  const defaultConfig = {
7
10
  projectId: "your-firebase-project-id",
8
11
  serviceAccountPath: "./serviceAccountKey.json",
@@ -29,7 +32,8 @@ function validateConfig(config) {
29
32
  function parseCollections(value) {
30
33
  return value
31
34
  .split(",")
32
- .map((collection) => collection.trim());
35
+ .map((collection) => collection.trim())
36
+ .filter((collection) => collection !== "");
33
37
  }
34
38
  function getServiceAccountUrl(projectId) {
35
39
  return `https://console.firebase.google.com/project/${encodeURIComponent(projectId)}/settings/serviceaccounts/adminsdk`;
@@ -54,20 +58,145 @@ function printMissingServiceAccountInfo(serviceAccountPath) {
54
58
  console.log(`Save the downloaded JSON key at: ${serviceAccountPath}`);
55
59
  console.log("");
56
60
  }
61
+ function gitignorePathFor(filePath) {
62
+ return filePath.replace(/\\/g, "/").replace(/^\.\//, "");
63
+ }
64
+ function printDetectedProjectCandidates(candidates) {
65
+ if (candidates.length === 0) {
66
+ return;
67
+ }
68
+ console.log("Detected Firebase project IDs:");
69
+ console.log("");
70
+ candidates.forEach((candidate, index) => {
71
+ console.log(`${index + 1}. ${candidate.projectId} from ${candidate.source}`);
72
+ });
73
+ console.log("");
74
+ }
75
+ async function promptForProjectId(rl, candidates) {
76
+ const projectIds = uniqueProjectIds(candidates);
77
+ if (projectIds.length === 0) {
78
+ return (await rl.question("Firebase project ID: ")).trim();
79
+ }
80
+ printDetectedProjectCandidates(candidates);
81
+ if (projectIds.length === 1) {
82
+ return (await rl.question(`Firebase project ID (${projectIds[0]}): `)).trim() || projectIds[0];
83
+ }
84
+ const answer = (await rl.question("Select Firebase project ID by number or enter one manually: ")).trim();
85
+ const selection = Number(answer);
86
+ if (Number.isInteger(selection) && selection >= 1 && selection <= candidates.length) {
87
+ return candidates[selection - 1].projectId;
88
+ }
89
+ return answer;
90
+ }
91
+ function suggestedServiceAccountPath(detectedPaths) {
92
+ return detectedPaths[0] ?? defaultConfig.serviceAccountPath;
93
+ }
94
+ function printDetectedServiceAccounts(detectedPaths) {
95
+ if (detectedPaths.length === 0) {
96
+ return;
97
+ }
98
+ console.log("Detected possible service account files:");
99
+ console.log("");
100
+ detectedPaths.forEach((filePath, index) => {
101
+ console.log(`${index + 1}. ${filePath}`);
102
+ });
103
+ console.log("");
104
+ }
105
+ async function promptForServiceAccountPath(rl, detectedPaths) {
106
+ printDetectedServiceAccounts(detectedPaths);
107
+ const suggestedPath = suggestedServiceAccountPath(detectedPaths);
108
+ const answer = (await rl.question(`Service account path (${suggestedPath}): `)).trim();
109
+ const selection = Number(answer);
110
+ if (detectedPaths.length > 0 &&
111
+ Number.isInteger(selection) &&
112
+ selection >= 1 &&
113
+ selection <= detectedPaths.length) {
114
+ return detectedPaths[selection - 1];
115
+ }
116
+ return answer || suggestedPath;
117
+ }
118
+ function parseSelectedCollections(inputValue, detectedCollections) {
119
+ const selectedCollections = [];
120
+ for (const item of inputValue.split(",")) {
121
+ const value = item.trim();
122
+ if (value === "") {
123
+ continue;
124
+ }
125
+ const selection = Number(value);
126
+ if (Number.isInteger(selection) &&
127
+ selection >= 1 &&
128
+ selection <= detectedCollections.length) {
129
+ selectedCollections.push(detectedCollections[selection - 1]);
130
+ continue;
131
+ }
132
+ selectedCollections.push(value);
133
+ }
134
+ return [...new Set(selectedCollections)];
135
+ }
136
+ async function promptForCollectionListing(rl, projectId, serviceAccountPath) {
137
+ if (!existsSync(serviceAccountPath)) {
138
+ console.log(`Service account file is not present, so collection detection is skipped: ${serviceAccountPath}`);
139
+ console.log("");
140
+ return undefined;
141
+ }
142
+ const answer = (await rl.question("Try to list Firestore collections with this service account? (y/N): "))
143
+ .trim()
144
+ .toLowerCase();
145
+ if (answer !== "y" && answer !== "yes") {
146
+ return undefined;
147
+ }
148
+ console.log("Connecting to Firestore to list top-level collections...");
149
+ let detectedCollections;
150
+ try {
151
+ detectedCollections = await listFirestoreCollections(projectId, serviceAccountPath);
152
+ }
153
+ catch (error) {
154
+ const message = error instanceof Error ? error.message : String(error);
155
+ console.log(`Could not list Firestore collections: ${message}`);
156
+ console.log("You can enter collection names manually.");
157
+ console.log("");
158
+ return undefined;
159
+ }
160
+ if (detectedCollections.length === 0) {
161
+ console.log("No top-level Firestore collections were detected.");
162
+ console.log("");
163
+ return undefined;
164
+ }
165
+ console.log("");
166
+ console.log("Detected Firestore collections:");
167
+ console.log("");
168
+ detectedCollections.forEach((collection, index) => {
169
+ console.log(`${index + 1}. ${collection}`);
170
+ });
171
+ console.log("");
172
+ const selected = (await rl.question("Collections to back up, comma-separated numbers or names: ")).trim();
173
+ if (selected === "") {
174
+ return undefined;
175
+ }
176
+ return parseSelectedCollections(selected, detectedCollections);
177
+ }
57
178
  async function promptForConfig(options, rl) {
179
+ const projectCandidates = detectFirebaseProjectCandidates();
180
+ const serviceAccountPaths = detectServiceAccountPaths();
58
181
  if (options.yes) {
59
- return defaultConfig;
182
+ return {
183
+ ...defaultConfig,
184
+ projectId: uniqueProjectIds(projectCandidates)[0] ?? defaultConfig.projectId,
185
+ };
60
186
  }
61
187
  if (!rl) {
62
188
  throw new Error("Prompt interface is required for interactive init.");
63
189
  }
64
- const projectId = (await rl.question("Firebase project ID: ")).trim();
190
+ const projectId = await promptForProjectId(rl, projectCandidates);
65
191
  if (projectId !== "") {
66
192
  printServiceAccountGuidance(projectId, defaultConfig.serviceAccountPath);
67
193
  }
68
- const serviceAccountPath = (await rl.question(`Service account path (${defaultConfig.serviceAccountPath}): `)).trim() || defaultConfig.serviceAccountPath;
194
+ const serviceAccountPath = await promptForServiceAccountPath(rl, serviceAccountPaths);
69
195
  const outputDir = (await rl.question(`Output directory (${defaultConfig.outputDir}): `)).trim() || defaultConfig.outputDir;
70
- const collectionsInput = (await rl.question("Collections, comma-separated: ")).trim();
196
+ const detectedCollections = await promptForCollectionListing(rl, projectId, serviceAccountPath);
197
+ const collectionsInput = detectedCollections
198
+ ? detectedCollections.join(",")
199
+ : (await rl.question("Collections, comma-separated: ")).trim();
71
200
  return {
72
201
  projectId,
73
202
  serviceAccountPath,
@@ -96,7 +225,7 @@ function ensureGitignoreEntries(entries) {
96
225
  .split("\n")
97
226
  .map((line) => line.trim())
98
227
  .filter((line) => line !== ""));
99
- const missingEntries = entries.filter((entry) => !existingLines.has(entry));
228
+ const missingEntries = [...new Set(entries)].filter((entry) => !existingLines.has(entry));
100
229
  if (missingEntries.length === 0) {
101
230
  return;
102
231
  }
@@ -137,6 +266,7 @@ export async function runInit(options) {
137
266
  writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`);
138
267
  ensureGitignoreEntries([
139
268
  "serviceAccountKey.json",
269
+ gitignorePathFor(config.serviceAccountPath),
140
270
  "firestore-backups/",
141
271
  "firestore-debug.log",
142
272
  ]);
@@ -0,0 +1,79 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ const projectConfigFiles = [
3
+ ".env",
4
+ ".env.local",
5
+ ".env.development",
6
+ ".env.production",
7
+ "firebase.json",
8
+ "src/firebase.ts",
9
+ "src/firebase.js",
10
+ "firebase.ts",
11
+ "firebase.js",
12
+ "src/lib/firebase.ts",
13
+ "src/lib/firebase.js",
14
+ "app/firebase.ts",
15
+ "app/firebase.js",
16
+ ];
17
+ const projectKeys = [
18
+ "VITE_FIREBASE_PROJECT_ID",
19
+ "NEXT_PUBLIC_FIREBASE_PROJECT_ID",
20
+ "REACT_APP_FIREBASE_PROJECT_ID",
21
+ "FIREBASE_PROJECT_ID",
22
+ "GCLOUD_PROJECT",
23
+ "projectId",
24
+ "project_id",
25
+ ];
26
+ function stripQuotes(value) {
27
+ return value.trim().replace(/^["']|["']$/g, "");
28
+ }
29
+ function findKeyValue(content, key) {
30
+ const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
31
+ const patterns = [
32
+ new RegExp(`(?:^|\\n)\\s*${escapedKey}\\s*=\\s*["']?([^"'\\n#]+)["']?`, "g"),
33
+ new RegExp(`${escapedKey}\\s*[:=]\\s*["']([^"']+)["']`, "g"),
34
+ ];
35
+ const values = [];
36
+ for (const pattern of patterns) {
37
+ for (const match of content.matchAll(pattern)) {
38
+ const value = stripQuotes(match[1] ?? "");
39
+ if (value !== "") {
40
+ values.push(value);
41
+ }
42
+ }
43
+ }
44
+ return values;
45
+ }
46
+ export function detectFirebaseProjectCandidates() {
47
+ const candidates = [];
48
+ const seen = new Set();
49
+ for (const filePath of projectConfigFiles) {
50
+ if (!existsSync(filePath)) {
51
+ continue;
52
+ }
53
+ let content;
54
+ try {
55
+ content = readFileSync(filePath, "utf-8");
56
+ }
57
+ catch {
58
+ continue;
59
+ }
60
+ for (const key of projectKeys) {
61
+ for (const projectId of findKeyValue(content, key)) {
62
+ const dedupeKey = `${projectId}\0${filePath}\0${key}`;
63
+ if (seen.has(dedupeKey)) {
64
+ continue;
65
+ }
66
+ seen.add(dedupeKey);
67
+ candidates.push({
68
+ projectId,
69
+ source: filePath,
70
+ key,
71
+ });
72
+ }
73
+ }
74
+ }
75
+ return candidates;
76
+ }
77
+ export function uniqueProjectIds(candidates) {
78
+ return [...new Set(candidates.map((candidate) => candidate.projectId))];
79
+ }
@@ -0,0 +1,10 @@
1
+ import { existsSync } from "node:fs";
2
+ const likelyServiceAccountPaths = [
3
+ "./serviceAccountKey.json",
4
+ "./service-account.json",
5
+ "./firebase-service-account.json",
6
+ "./credentials/firebase.json",
7
+ ];
8
+ export function detectServiceAccountPaths() {
9
+ return likelyServiceAccountPaths.filter((filePath) => existsSync(filePath));
10
+ }
@@ -0,0 +1,33 @@
1
+ import admin from "firebase-admin";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ export async function listFirestoreCollections(projectId, serviceAccountPath) {
4
+ if (!existsSync(serviceAccountPath)) {
5
+ throw new Error(`Service account file not found: ${serviceAccountPath}`);
6
+ }
7
+ const emulatorHost = process.env.FIRESTORE_EMULATOR_HOST;
8
+ let appOptions;
9
+ if (emulatorHost) {
10
+ appOptions = { projectId };
11
+ }
12
+ else {
13
+ let serviceAccount;
14
+ try {
15
+ serviceAccount = JSON.parse(readFileSync(serviceAccountPath, "utf-8"));
16
+ }
17
+ catch {
18
+ throw new Error(`Invalid service account file: ${serviceAccountPath}`);
19
+ }
20
+ appOptions = {
21
+ credential: admin.credential.cert(serviceAccount),
22
+ projectId,
23
+ };
24
+ }
25
+ const app = admin.initializeApp(appOptions, `firevault-init-${Date.now()}`);
26
+ try {
27
+ const collections = await app.firestore().listCollections();
28
+ return collections.map((collection) => collection.id).sort();
29
+ }
30
+ finally {
31
+ await app.delete();
32
+ }
33
+ }
@@ -82,8 +82,9 @@ Current implementation notes:
82
82
  - `loadConfig` reads and parses `firevault.config.json`.
83
83
  - Firebase initialization expects `serviceAccountPath`.
84
84
  - `firevault init` guides setup, validates required fields, checks Git state before writing, and updates `.gitignore` without overwriting existing entries.
85
+ - `firevault init` can suggest project IDs from local Firebase config files and likely service account paths from local filenames.
85
86
  - `firevault init --force` allows dirty Git state and config overwrite with a warning.
86
- - `firevault init --yes` provides a non-interactive path for tests and automation.
87
+ - `firevault init --yes` provides a deterministic non-interactive path for tests and automation, using a detected project ID if one is available and skipping Firebase collection listing.
87
88
 
88
89
  ## Init Safety
89
90
 
@@ -94,11 +95,15 @@ Behavior:
94
95
  - prints the Firevault identity before prompting,
95
96
  - detects whether the current directory is inside a Git repository,
96
97
  - offers `git init` when no repository exists,
98
+ - scans common local Firebase files for project ID candidates,
99
+ - shows detected project ID candidates with their source files,
100
+ - suggests likely service account paths without reading or printing private key contents,
97
101
  - prints the Firebase Console Admin SDK service account URL for the entered project ID,
98
102
  - explains where to save the manually downloaded service account key,
103
+ - optionally lists top-level Firestore collections only after telling the user and only when the selected service account file exists,
99
104
  - refuses to run in a dirty Git working tree unless `--force` is provided,
100
105
  - refuses to overwrite `firevault.config.json` unless `--force` is provided,
101
- - appends `.gitignore` safety entries without duplicating existing lines,
106
+ - appends `.gitignore` safety entries, including the selected service account path, without duplicating existing lines,
102
107
  - never creates service accounts, opens browsers, runs `gcloud`, commits, pushes, creates GitHub repositories, contacts Firebase, or writes secrets.
103
108
 
104
109
  ## Firebase Access
package/docs/roadmap.md CHANGED
@@ -26,7 +26,7 @@ Status:
26
26
  - npm prerelease packaging is guarded by package file whitelisting and pack verification.
27
27
  - Local npm prerelease publishing is guarded by a `gitversionjs`-based publish script with clean-tree, build, emulator-test, pack, and forbidden-path checks.
28
28
  - Public GitHub release docs cover quick start, security, contributing, and issue triage.
29
- - Guided `firevault init` validates setup input, checks Git state, and applies `.gitignore` safety entries.
29
+ - Guided `firevault init` validates setup input, checks Git state, suggests local Firebase project settings, optionally lists Firestore collections, and applies `.gitignore` safety entries.
30
30
 
31
31
  Next work:
32
32
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "firevault",
3
- "version": "0.1.1-beta.2",
3
+ "version": "0.1.1-beta.3",
4
4
  "description": "Undo button for Firestore. Git-style history, rollback, and recovery for Firestore projects.",
5
5
  "keywords": [
6
6
  "firebase",