@firebase-function-kits/delete-user-data 0.0.1 → 0.0.2-rc.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.
Files changed (76) hide show
  1. package/CHANGELOG.md +1 -0
  2. package/README.md +151 -0
  3. package/lib/config.d.ts +22 -0
  4. package/lib/config.d.ts.map +1 -0
  5. package/lib/config.js +86 -0
  6. package/lib/config.js.map +1 -0
  7. package/lib/events.d.ts +18 -0
  8. package/lib/events.d.ts.map +1 -0
  9. package/lib/events.js +71 -0
  10. package/lib/events.js.map +1 -0
  11. package/lib/export-config.d.ts +55 -0
  12. package/lib/export-config.d.ts.map +1 -0
  13. package/lib/export-config.js +56 -0
  14. package/lib/export-config.js.map +1 -0
  15. package/lib/handlers.d.ts +35 -0
  16. package/lib/handlers.d.ts.map +1 -0
  17. package/lib/handlers.js +243 -0
  18. package/lib/handlers.js.map +1 -0
  19. package/lib/helpers.d.ts +19 -0
  20. package/lib/helpers.d.ts.map +1 -0
  21. package/lib/helpers.js +39 -0
  22. package/lib/helpers.js.map +1 -0
  23. package/lib/index.d.ts +6 -0
  24. package/lib/index.d.ts.map +1 -0
  25. package/lib/index.js +112 -0
  26. package/lib/index.js.map +1 -0
  27. package/lib/lib.d.ts +23 -0
  28. package/lib/lib.d.ts.map +1 -0
  29. package/lib/lib.js +38 -0
  30. package/lib/lib.js.map +1 -0
  31. package/lib/logs.d.ts +26 -0
  32. package/lib/logs.d.ts.map +1 -0
  33. package/lib/logs.js +116 -0
  34. package/lib/logs.js.map +1 -0
  35. package/lib/recursiveDelete.d.ts +18 -0
  36. package/lib/recursiveDelete.d.ts.map +1 -0
  37. package/lib/recursiveDelete.js +37 -0
  38. package/lib/recursiveDelete.js.map +1 -0
  39. package/lib/runBatchPubSubDeletions.d.ts +27 -0
  40. package/lib/runBatchPubSubDeletions.d.ts.map +1 -0
  41. package/lib/runBatchPubSubDeletions.js +47 -0
  42. package/lib/runBatchPubSubDeletions.js.map +1 -0
  43. package/lib/runCustomSearchFunction.d.ts +18 -0
  44. package/lib/runCustomSearchFunction.d.ts.map +1 -0
  45. package/lib/runCustomSearchFunction.js +78 -0
  46. package/lib/runCustomSearchFunction.js.map +1 -0
  47. package/lib/search.d.ts +19 -0
  48. package/lib/search.d.ts.map +1 -0
  49. package/lib/search.js +29 -0
  50. package/lib/search.js.map +1 -0
  51. package/package.json +37 -4
  52. package/src/config.ts +98 -0
  53. package/src/events.ts +38 -0
  54. package/src/export-config.ts +112 -0
  55. package/src/handlers.ts +271 -0
  56. package/src/helpers.ts +42 -0
  57. package/src/index.ts +100 -0
  58. package/src/lib.ts +41 -0
  59. package/src/logs.ts +127 -0
  60. package/src/recursiveDelete.ts +42 -0
  61. package/src/runBatchPubSubDeletions.ts +66 -0
  62. package/src/runCustomSearchFunction.ts +50 -0
  63. package/src/search.ts +37 -0
  64. package/tests/config.test.ts +180 -0
  65. package/tests/export-config.test.ts +117 -0
  66. package/tests/fakes.ts +325 -0
  67. package/tests/handlers.test.ts +517 -0
  68. package/tests/helpers.test.ts +126 -0
  69. package/tests/lib.test.ts +40 -0
  70. package/tests/recursiveDelete.test.ts +102 -0
  71. package/tests/runBatchPubSubDeletions.test.ts +164 -0
  72. package/tests/runCustomSearchFunction.test.ts +125 -0
  73. package/tests/search.test.ts +127 -0
  74. package/tsconfig.json +18 -0
  75. package/tsconfig.tsbuildinfo +1 -0
  76. package/index.js +0 -0
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Copyright 2026 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import type * as admin from "firebase-admin";
18
+
19
+ const MAX_RETRY_ATTEMPTS = 3;
20
+
21
+ export const recursiveDelete = async (
22
+ path: string,
23
+ db: admin.firestore.Firestore
24
+ ) => {
25
+ // Recursively delete a reference and log the references of failures.
26
+ const bulkWriter = db.bulkWriter();
27
+
28
+ bulkWriter.onWriteError((error) => {
29
+ if (error.failedAttempts < MAX_RETRY_ATTEMPTS) {
30
+ return true;
31
+ } else {
32
+ console.warn("Failed to delete document: ", error.documentRef.path);
33
+ return false;
34
+ }
35
+ });
36
+
37
+ const isDocument = path.split("/").length % 2 === 0;
38
+
39
+ const reference = isDocument ? db.doc(path) : db.collection(path);
40
+
41
+ await db.recursiveDelete(reference, bulkWriter);
42
+ };
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Copyright 2026 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import type { PubSub } from "@google-cloud/pubsub";
18
+ import chunk from "lodash.chunk";
19
+ import type { ResolvedDeleteUserDataConfig } from "./export-config";
20
+
21
+ export interface DeletionPaths {
22
+ firestorePaths: string[];
23
+ }
24
+
25
+ export interface PublisherContext {
26
+ pubsub: PubSub;
27
+ config: ResolvedDeleteUserDataConfig;
28
+ }
29
+
30
+ function topicPath(
31
+ config: ResolvedDeleteUserDataConfig,
32
+ topicName: string
33
+ ): string {
34
+ const projectId =
35
+ config.projectId ??
36
+ process.env.GOOGLE_CLOUD_PROJECT ??
37
+ process.env.PROJECT_ID;
38
+ return projectId ? `projects/${projectId}/topics/${topicName}` : topicName;
39
+ }
40
+
41
+ export async function publishSearch(
42
+ uid: string,
43
+ depth: number,
44
+ path: string,
45
+ ctx: PublisherContext
46
+ ): Promise<void> {
47
+ await ctx.pubsub
48
+ .topic(topicPath(ctx.config, ctx.config.discoveryTopicName))
49
+ .publishMessage({ json: { path, uid, depth } });
50
+ }
51
+
52
+ export async function runBatchPubSubDeletions(
53
+ paths: DeletionPaths,
54
+ uid: string,
55
+ ctx: PublisherContext
56
+ ): Promise<void> {
57
+ const { firestorePaths } = paths;
58
+ if (!firestorePaths || !Array.isArray(firestorePaths)) return;
59
+ if (firestorePaths.length === 0) return;
60
+
61
+ for (const chunkedPaths of chunk<string>(firestorePaths, 450)) {
62
+ await ctx.pubsub
63
+ .topic(topicPath(ctx.config, ctx.config.deletionTopicName))
64
+ .publishMessage({ json: { paths: chunkedPaths, uid } });
65
+ }
66
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Copyright 2026 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import fetch from "node-fetch";
18
+ import * as logs from "./logs";
19
+ import type { PublisherContext } from "./runBatchPubSubDeletions";
20
+ import { runBatchPubSubDeletions } from "./runBatchPubSubDeletions";
21
+
22
+ export const runCustomSearchFunction = async (
23
+ uid: string,
24
+ ctx: PublisherContext
25
+ ): Promise<void> => {
26
+ if (!ctx.config.searchFunction) return;
27
+
28
+ const response = await fetch(ctx.config.searchFunction, {
29
+ method: "POST",
30
+ body: JSON.stringify({ uid }),
31
+ headers: { "Content-Type": "application/json" },
32
+ });
33
+
34
+ if (!response.ok) {
35
+ const body = await response.text();
36
+ logs.customFunctionError(new Error(body));
37
+ return;
38
+ }
39
+
40
+ const json = await response.json();
41
+ if (Array.isArray(json)) {
42
+ return runBatchPubSubDeletions({ firestorePaths: json }, uid, ctx);
43
+ }
44
+
45
+ return runBatchPubSubDeletions(
46
+ json as { firestorePaths: string[] },
47
+ uid,
48
+ ctx
49
+ );
50
+ };
package/src/search.ts ADDED
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Copyright 2026 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import type * as admin from "firebase-admin";
18
+ import {
19
+ type PublisherContext,
20
+ publishSearch,
21
+ } from "./runBatchPubSubDeletions";
22
+
23
+ export const search = async (
24
+ uid: string,
25
+ depth: number,
26
+ db: admin.firestore.Firestore,
27
+ ctx: PublisherContext,
28
+ document?: admin.firestore.DocumentReference<admin.firestore.DocumentData>
29
+ ): Promise<void> => {
30
+ const collections = !document
31
+ ? await db.listCollections()
32
+ : await document.listCollections();
33
+
34
+ for (const collection of collections) {
35
+ await publishSearch(uid, depth, collection.path, ctx);
36
+ }
37
+ };
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Copyright 2026 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import { afterEach, describe, expect, test, vi } from "vitest";
18
+
19
+ class FakeExpression<_T = string> {
20
+ constructor(private readonly cel: string) {}
21
+
22
+ toCEL(): string {
23
+ return this.cel;
24
+ }
25
+ }
26
+
27
+ class FakeStringParam extends FakeExpression<string> {
28
+ constructor(
29
+ private readonly name: string,
30
+ private readonly defaultValue?: string | FakeExpression
31
+ ) {
32
+ super(`{{ params.${name} }}`);
33
+ }
34
+
35
+ value(): string {
36
+ if (this.defaultValue instanceof FakeStringParam) {
37
+ return this.defaultValue.value();
38
+ }
39
+ if (this.defaultValue instanceof FakeExpression) {
40
+ return this.defaultValue.toCEL();
41
+ }
42
+ return this.defaultValue ?? `${this.name.toLowerCase()}-value`;
43
+ }
44
+ }
45
+
46
+ const defineString = vi.fn(
47
+ (name: string, opts?: { default?: string | FakeExpression }) =>
48
+ new FakeStringParam(name, opts?.default)
49
+ );
50
+
51
+ const defineInt = vi.fn((_name: string, opts?: { default?: number }) => ({
52
+ value: () => opts?.default ?? 0,
53
+ }));
54
+
55
+ const defineBoolean = vi.fn((_name: string, opts?: { default?: boolean }) => ({
56
+ value: () => opts?.default ?? false,
57
+ }));
58
+
59
+ const expr = vi.fn(
60
+ (strings: TemplateStringsArray, ...values: unknown[]) =>
61
+ new FakeExpression(
62
+ strings.reduce(
63
+ (result, part, index) =>
64
+ result + part + (index < values.length ? cel(values[index]) : ""),
65
+ ""
66
+ )
67
+ )
68
+ );
69
+
70
+ function cel(value: unknown): string {
71
+ return value instanceof FakeExpression ? value.toCEL() : String(value);
72
+ }
73
+
74
+ vi.mock("firebase-functions/params", () => ({
75
+ Expression: FakeExpression,
76
+ defineBoolean,
77
+ defineInt,
78
+ defineString,
79
+ expr,
80
+ projectID: { value: () => "demo-test" },
81
+ select: vi.fn((options: string[]) => ({ options })),
82
+ storageBucket: new FakeStringParam("STORAGE_BUCKET", "demo-test.appspot.com"),
83
+ }));
84
+
85
+ async function importConfig() {
86
+ vi.resetModules();
87
+ defineString.mockClear();
88
+ defineInt.mockClear();
89
+ defineBoolean.mockClear();
90
+ expr.mockClear();
91
+
92
+ return import("../src/config");
93
+ }
94
+
95
+ afterEach(() => {
96
+ vi.unstubAllEnvs();
97
+ });
98
+
99
+ describe("configFromEnv", () => {
100
+ test("reads the extension.yaml defaults", async () => {
101
+ const { configFromEnv } = await importConfig();
102
+
103
+ expect(configFromEnv()).toMatchObject({
104
+ firestoreDatabaseId: "(default)",
105
+ firestoreDeleteMode: "shallow",
106
+ rtdbLocation: "us-central1",
107
+ enableAutoDiscovery: false,
108
+ searchDepth: 3,
109
+ searchFields: "id,uid,userId",
110
+ projectId: "demo-test",
111
+ });
112
+ });
113
+
114
+ test("maps empty params to undefined", async () => {
115
+ const { configFromEnv } = await importConfig();
116
+ const config = configFromEnv();
117
+
118
+ expect(config.firestorePaths).toBeUndefined();
119
+ expect(config.rtdbPaths).toBeUndefined();
120
+ expect(config.storagePaths).toBeUndefined();
121
+ expect(config.searchFunction).toBeUndefined();
122
+ expect(config.rtdbInstance).toBeUndefined();
123
+ });
124
+
125
+ test("declares the params the extension exposes", async () => {
126
+ await importConfig();
127
+
128
+ const declared = defineString.mock.calls.map(([name]) => name);
129
+ expect(declared).toEqual(
130
+ expect.arrayContaining([
131
+ "INSTANCE_ID",
132
+ "FIRESTORE_PATHS",
133
+ "FIRESTORE_DATABASE_ID",
134
+ "FIRESTORE_DELETE_MODE",
135
+ "SELECTED_DATABASE_INSTANCE",
136
+ "SELECTED_DATABASE_LOCATION",
137
+ "RTDB_PATHS",
138
+ "CLOUD_STORAGE_BUCKET",
139
+ "STORAGE_PATHS",
140
+ "AUTO_DISCOVERY_SEARCH_FIELDS",
141
+ "SEARCH_FUNCTION",
142
+ "DISCOVERY_TOPIC_NAME",
143
+ "DELETION_TOPIC_NAME",
144
+ ])
145
+ );
146
+ expect(defineInt.mock.calls).toContainEqual([
147
+ "AUTO_DISCOVERY_SEARCH_DEPTH",
148
+ { default: 3 },
149
+ ]);
150
+ expect(defineBoolean.mock.calls).toContainEqual([
151
+ "ENABLE_AUTO_DISCOVERY",
152
+ { default: false },
153
+ ]);
154
+ });
155
+
156
+ test("defaults the topic names to kit-{instanceId}-* expressions", async () => {
157
+ const { CONFIG_EXPRESSIONS } = await importConfig();
158
+
159
+ expect(cel(CONFIG_EXPRESSIONS.discoveryTopicName)).toBe(
160
+ "{{ params.DISCOVERY_TOPIC_NAME }}"
161
+ );
162
+ expect(cel(CONFIG_EXPRESSIONS.deletionTopicName)).toBe(
163
+ "{{ params.DELETION_TOPIC_NAME }}"
164
+ );
165
+ expect(expr.mock.results.map((result) => cel(result.value))).toEqual([
166
+ "kit-{{ params.INSTANCE_ID }}-discovery",
167
+ "kit-{{ params.INSTANCE_ID }}-deletion",
168
+ ]);
169
+ expect(defineString.mock.calls).toContainEqual([
170
+ "DISCOVERY_TOPIC_NAME",
171
+ { default: expect.anything() },
172
+ ]);
173
+ });
174
+
175
+ test("defaults the storage bucket to the project bucket param", async () => {
176
+ const { configFromEnv } = await importConfig();
177
+
178
+ expect(configFromEnv().storageBucket).toBe("demo-test.appspot.com");
179
+ });
180
+ });
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Copyright 2026 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import { describe, expect, test } from "vitest";
18
+ import {
19
+ getDatabaseUrl,
20
+ resolveDeleteUserDataConfig,
21
+ } from "../src/export-config";
22
+
23
+ // Parity: delete-user-data/functions/__tests__/helpers.test.ts
24
+ // ("Test Realtime Database URL helper function"). The helper moved from
25
+ // `helpers.ts` to `export-config.ts` in the kit; the cases are unchanged.
26
+ describe("getDatabaseUrl", () => {
27
+ test("returns the correct url for us-central1", () => {
28
+ expect(getDatabaseUrl("server-name", "us-central1")).toBe(
29
+ "https://server-name.firebaseio.com"
30
+ );
31
+ });
32
+
33
+ test("returns the correct url for europe-west1", () => {
34
+ expect(getDatabaseUrl("server-name", "europe-west1")).toBe(
35
+ "https://server-name.europe-west1.firebasedatabase.app"
36
+ );
37
+ });
38
+
39
+ test("returns the correct url for asia-southeast1", () => {
40
+ expect(getDatabaseUrl("server-name", "asia-southeast1")).toBe(
41
+ "https://server-name.asia-southeast1.firebasedatabase.app"
42
+ );
43
+ });
44
+
45
+ test("returns null if the instance is undefined", () => {
46
+ expect(getDatabaseUrl(undefined, "asia-southeast1")).toBe(null);
47
+ });
48
+
49
+ test("returns null if the location is undefined", () => {
50
+ expect(getDatabaseUrl("server-name", undefined)).toBe(null);
51
+ });
52
+ });
53
+
54
+ describe("resolveDeleteUserDataConfig", () => {
55
+ test("applies the extension.yaml defaults", () => {
56
+ const config = resolveDeleteUserDataConfig({ instanceId: "my-instance" });
57
+
58
+ expect(config.firestoreDatabaseId).toBe("(default)");
59
+ expect(config.firestoreDeleteMode).toBe("shallow");
60
+ expect(config.enableAutoDiscovery).toBe(false);
61
+ expect(config.searchDepth).toBe(3);
62
+ expect(config.searchFields).toBe("id,uid,userId");
63
+ });
64
+
65
+ test("derives topic names from the instance id", () => {
66
+ const config = resolveDeleteUserDataConfig({ instanceId: "my-instance" });
67
+
68
+ expect(config.discoveryTopicName).toBe("kit-my-instance-discovery");
69
+ expect(config.deletionTopicName).toBe("kit-my-instance-deletion");
70
+ });
71
+
72
+ test("honours explicit topic names", () => {
73
+ const config = resolveDeleteUserDataConfig({
74
+ instanceId: "my-instance",
75
+ discoveryTopicName: "custom-discovery",
76
+ deletionTopicName: "custom-deletion",
77
+ });
78
+
79
+ expect(config.discoveryTopicName).toBe("custom-discovery");
80
+ expect(config.deletionTopicName).toBe("custom-deletion");
81
+ });
82
+
83
+ test("passes through the supplied values", () => {
84
+ const config = resolveDeleteUserDataConfig({
85
+ instanceId: "my-instance",
86
+ firestorePaths: "users/{UID}",
87
+ firestoreDatabaseId: "secondary",
88
+ firestoreDeleteMode: "recursive",
89
+ rtdbInstance: "server-name",
90
+ rtdbLocation: "europe-west1",
91
+ rtdbPaths: "users/{UID}",
92
+ storageBucket: "my-bucket",
93
+ storagePaths: "{DEFAULT}/{UID}",
94
+ enableAutoDiscovery: true,
95
+ searchDepth: 5,
96
+ searchFields: "uid",
97
+ searchFunction: "https://example.com/search",
98
+ projectId: "demo-test",
99
+ });
100
+
101
+ expect(config).toMatchObject({
102
+ firestorePaths: "users/{UID}",
103
+ firestoreDatabaseId: "secondary",
104
+ firestoreDeleteMode: "recursive",
105
+ rtdbInstance: "server-name",
106
+ rtdbLocation: "europe-west1",
107
+ rtdbPaths: "users/{UID}",
108
+ storageBucket: "my-bucket",
109
+ storagePaths: "{DEFAULT}/{UID}",
110
+ enableAutoDiscovery: true,
111
+ searchDepth: 5,
112
+ searchFields: "uid",
113
+ searchFunction: "https://example.com/search",
114
+ projectId: "demo-test",
115
+ });
116
+ });
117
+ });