@donotdev/functions 0.2.3 → 0.3.1

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 (114) hide show
  1. package/guidelines/VERCEL.md +2 -2
  2. package/lib/chunks/{chunk-UH445BGK.js → chunk-2N73OZFE.js} +2 -2
  3. package/lib/chunks/chunk-472JD6X7.js +22 -0
  4. package/lib/chunks/chunk-472JD6X7.js.map +7 -0
  5. package/lib/chunks/{chunk-QXIOO2RL.js → chunk-BTWJEJCV.js} +2 -2
  6. package/lib/chunks/chunk-CN6WXKYF.js +22 -0
  7. package/lib/chunks/chunk-CN6WXKYF.js.map +7 -0
  8. package/lib/chunks/{chunk-GDIUOJMD.js → chunk-DGBZDD6D.js} +2 -2
  9. package/lib/chunks/chunk-GBZQPOX4.js +151 -0
  10. package/lib/chunks/{chunk-F3WBFWPO.js.map → chunk-GBZQPOX4.js.map} +3 -3
  11. package/lib/chunks/chunk-ORBGTVJI.js +22 -0
  12. package/lib/chunks/{chunk-EZKRLLSQ.js.map → chunk-ORBGTVJI.js.map} +1 -1
  13. package/lib/chunks/chunk-R3I7U5QT.js +22 -0
  14. package/lib/chunks/chunk-R3I7U5QT.js.map +7 -0
  15. package/lib/chunks/{chunk-6NXIK35R.js → chunk-XWMG2FWZ.js} +2 -2
  16. package/lib/chunks/{chunk-6NXIK35R.js.map → chunk-XWMG2FWZ.js.map} +1 -1
  17. package/lib/chunks/chunk-ZCY6GTIC.js +22 -0
  18. package/lib/chunks/chunk-ZCY6GTIC.js.map +7 -0
  19. package/lib/chunks/{monitoring-LXNVBD3G.js → monitoring-KF7FRUQ6.js} +2 -2
  20. package/lib/chunks/{rateLimiter-GG5LPWXJ.js → rateLimiter-S7TITXOD.js} +2 -2
  21. package/lib/chunks/{server-NODQAE3F.js → server-SU4BVPPF.js} +2 -2
  22. package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
  23. package/lib/firebase/crud/create.d.ts +22 -1
  24. package/lib/firebase/crud/update.d.ts +27 -3
  25. package/lib/firebase/index.js +1 -1
  26. package/lib/firebase/index.js.map +3 -3
  27. package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -8
  28. package/lib/shared/billing/index.d.ts +2 -0
  29. package/lib/shared/billing/verifyOrderCheckout.d.ts +53 -0
  30. package/lib/shared/crud/bulkCore.d.ts +38 -10
  31. package/lib/shared/crud/index.d.ts +1 -0
  32. package/lib/shared/crud/written.d.ts +21 -0
  33. package/lib/shared/index.d.ts +0 -1
  34. package/lib/shared/index.js +1 -1
  35. package/lib/shared/utils.d.ts +0 -9
  36. package/lib/supabase/crud/bulk.d.ts +7 -0
  37. package/lib/supabase/crud/create.d.ts +5 -1
  38. package/lib/supabase/crud/entityStore.d.ts +54 -14
  39. package/lib/supabase/crud/update.d.ts +7 -2
  40. package/lib/supabase/index.d.ts +4 -0
  41. package/lib/supabase/index.js +1 -1
  42. package/lib/supabase/index.js.map +4 -4
  43. package/lib/vercel/api/crud/create.d.ts +6 -1
  44. package/lib/vercel/api/crud/update.d.ts +8 -1
  45. package/lib/vercel/api/index.js +1 -1
  46. package/package.json +3 -3
  47. package/src/firebase/auth/removeCustomClaims.ts +31 -1
  48. package/src/firebase/auth/setCustomClaims.ts +3 -0
  49. package/src/firebase/crud/__tests__/bulk.test.ts +50 -1
  50. package/src/firebase/crud/__tests__/create.test.ts +64 -0
  51. package/src/firebase/crud/__tests__/update.test.ts +97 -0
  52. package/src/firebase/crud/aggregate.ts +10 -21
  53. package/src/firebase/crud/bulk.ts +23 -10
  54. package/src/firebase/crud/create.ts +19 -18
  55. package/src/firebase/crud/get.ts +3 -12
  56. package/src/firebase/crud/list.ts +5 -4
  57. package/src/firebase/crud/update.ts +35 -19
  58. package/src/firebase/registerCrudFunctions.ts +1 -0
  59. package/src/shared/__tests__/bulkCore.test.ts +191 -0
  60. package/src/shared/__tests__/removeCustomClaims.test.ts +117 -0
  61. package/src/shared/__tests__/setCustomClaims.test.ts +103 -0
  62. package/src/shared/__tests__/utils.test.ts +0 -30
  63. package/src/shared/billing/__tests__/updateUserSubscription.test.ts +139 -0
  64. package/src/shared/billing/__tests__/verifyOrderCheckout.exports.test.ts +47 -0
  65. package/src/shared/billing/__tests__/verifyOrderCheckout.supabase.integration.test.ts +107 -0
  66. package/src/shared/billing/__tests__/verifyOrderCheckout.test.ts +233 -0
  67. package/src/shared/billing/helpers/updateUserSubscription.ts +10 -14
  68. package/src/shared/billing/index.ts +2 -0
  69. package/src/shared/billing/verifyOrderCheckout.ts +142 -0
  70. package/src/shared/crud/bulkCore.ts +110 -81
  71. package/src/shared/crud/index.ts +1 -0
  72. package/src/shared/crud/written.ts +56 -0
  73. package/src/shared/index.d.ts +0 -9
  74. package/src/shared/index.ts +0 -1
  75. package/src/shared/utils.ts +0 -43
  76. package/src/supabase/__tests__/bulk.test.ts +60 -2
  77. package/src/supabase/__tests__/create.test.ts +86 -0
  78. package/src/supabase/__tests__/entityStore.test.ts +91 -25
  79. package/src/supabase/__tests__/update.test.ts +107 -0
  80. package/src/supabase/auth/removeCustomClaims.ts +7 -2
  81. package/src/supabase/auth/setCustomClaims.ts +4 -2
  82. package/src/supabase/crud/bulk.ts +47 -0
  83. package/src/supabase/crud/create.ts +14 -24
  84. package/src/supabase/crud/entityStore.ts +106 -17
  85. package/src/supabase/crud/get.ts +3 -12
  86. package/src/supabase/crud/list.ts +5 -4
  87. package/src/supabase/crud/update.ts +20 -18
  88. package/src/supabase/index.ts +7 -0
  89. package/src/supabase/registerCrudFunctions.ts +1 -0
  90. package/src/vercel/__tests__/bulk.test.ts +16 -8
  91. package/src/vercel/api/crud/bulk.ts +27 -4
  92. package/src/vercel/api/crud/create.ts +17 -19
  93. package/src/vercel/api/crud/get.ts +5 -6
  94. package/src/vercel/api/crud/list.ts +4 -5
  95. package/src/vercel/api/crud/update.ts +20 -18
  96. package/lib/chunks/chunk-EZKRLLSQ.js +0 -22
  97. package/lib/chunks/chunk-F3PHE627.js +0 -22
  98. package/lib/chunks/chunk-F3PHE627.js.map +0 -7
  99. package/lib/chunks/chunk-F3WBFWPO.js +0 -151
  100. package/lib/chunks/chunk-G5DRV3DH.js +0 -22
  101. package/lib/chunks/chunk-G5DRV3DH.js.map +0 -7
  102. package/lib/chunks/chunk-Q2WLRFOE.js +0 -22
  103. package/lib/chunks/chunk-Q2WLRFOE.js.map +0 -7
  104. package/lib/chunks/chunk-W74UL7AY.js +0 -22
  105. package/lib/chunks/chunk-W74UL7AY.js.map +0 -7
  106. package/lib/shared/schema.d.ts +0 -56
  107. package/src/shared/__tests__/schema.test.ts +0 -219
  108. package/src/shared/schema.ts +0 -188
  109. /package/lib/chunks/{chunk-UH445BGK.js.map → chunk-2N73OZFE.js.map} +0 -0
  110. /package/lib/chunks/{chunk-QXIOO2RL.js.map → chunk-BTWJEJCV.js.map} +0 -0
  111. /package/lib/chunks/{chunk-GDIUOJMD.js.map → chunk-DGBZDD6D.js.map} +0 -0
  112. /package/lib/chunks/{monitoring-LXNVBD3G.js.map → monitoring-KF7FRUQ6.js.map} +0 -0
  113. /package/lib/chunks/{rateLimiter-GG5LPWXJ.js.map → rateLimiter-S7TITXOD.js.map} +0 -0
  114. /package/lib/chunks/{server-NODQAE3F.js.map → server-SU4BVPPF.js.map} +0 -0
@@ -15,11 +15,7 @@ import type {
15
15
  } from 'firebase-functions/v2/https';
16
16
  import * as v from 'valibot';
17
17
 
18
- import {
19
- filterVisibleFields,
20
- hasRoleAccess,
21
- HIDDEN_STATUSES,
22
- } from '@donotdev/core/server';
18
+ import { filterVisibleFields, isReadableBy } from '@donotdev/core/server';
23
19
  import type { EntityOwnershipConfig, UserRole } from '@donotdev/core/server';
24
20
  import { getFirebaseAdminFirestore } from '@donotdev/firebase/server';
25
21
 
@@ -62,14 +58,9 @@ function getEntityLogicFactory(
62
58
  throw new DoNotDevError('Entity not found', 'not-found');
63
59
  }
64
60
 
65
- const isAdmin = hasRoleAccess(userRole, 'admin'); // Uses role hierarchy
66
-
67
- // Hide drafts/deleted from non-admin users (security: hidden statuses never reach public)
61
+ // CRUD rule 4 (core/schemas crud/read): hidden statuses never reach non-admins
68
62
  const docData = doc.data();
69
- if (
70
- !isAdmin &&
71
- (HIDDEN_STATUSES as readonly string[]).includes(docData?.status)
72
- ) {
63
+ if (!isReadableBy(docData, userRole)) {
73
64
  throw new DoNotDevError('Entity not found', 'not-found');
74
65
  }
75
66
 
@@ -20,7 +20,7 @@ import * as v from 'valibot';
20
20
  import {
21
21
  filterVisibleFields,
22
22
  hasRoleAccess,
23
- HIDDEN_STATUSES,
23
+ hiddenStatusesFor,
24
24
  } from '@donotdev/core/server';
25
25
  import type {
26
26
  EntityOwnershipConfig,
@@ -91,9 +91,10 @@ function listEntitiesLogicFactory(
91
91
  const db = getFirebaseAdminFirestore();
92
92
  let query: Query = db.collection(collection);
93
93
 
94
- // Filter out hidden statuses for non-admin users (security: drafts/deleted never reach public)
95
- if (!isAdmin) {
96
- query = query.where('status', 'not-in', [...HIDDEN_STATUSES]);
94
+ // CRUD rule 4 (core/schemas crud/read): hidden statuses never reach non-admins
95
+ const hidden = hiddenStatusesFor(userRole);
96
+ if (hidden.length > 0) {
97
+ query = query.where('status', 'not-in', [...hidden]);
97
98
  }
98
99
 
99
100
  // Ownership: when set and not admin, listCard = public condition, list = mine filter
@@ -16,7 +16,7 @@ import type {
16
16
  } from 'firebase-functions/v2/https';
17
17
  import * as v from 'valibot';
18
18
 
19
- import { DEFAULT_STATUS_VALUE } from '@donotdev/core/server';
19
+ import { prepareUpdate } from '@donotdev/core/server';
20
20
  import type { UserRole, UniqueKeyDefinition } from '@donotdev/core/server';
21
21
  import { getFirebaseAdminFirestore } from '@donotdev/firebase/server';
22
22
 
@@ -25,7 +25,8 @@ import {
25
25
  transformFirestoreData,
26
26
  } from '../../shared/index.js';
27
27
  import { updateMetadata } from '../../shared/index.js';
28
- import { DoNotDevError, validateDocument } from '../../shared/utils.js';
28
+ import { writtenOf } from '../../shared/crud/written.js';
29
+ import { DoNotDevError } from '../../shared/utils.js';
29
30
  import { createBaseFunction } from '../baseFunction.js';
30
31
  import { CRUD_CONFIG } from '../config/constants.js';
31
32
 
@@ -136,13 +137,24 @@ async function checkUniqueKeysForUpdate(
136
137
  * Generic business logic for updating entities
137
138
  * Base function handles: validation, auth, rate limiting, monitoring
138
139
  *
139
- * @version 0.1.0
140
+ * Status rule: `prepareUpdate` (core/schemas crud/update). An update
141
+ * entering a visible status (`updateCheck`, e.g. a draft published) is checked
142
+ * whole: the merged document against the update schema (`validateWholeDocument`). The
143
+ * parse output of the sent keys is written, never the raw payload.
144
+ *
145
+ * @param collection - The Firestore collection name
146
+ * @param documentSchema - The update schema: validates `{ ...payload, id }` of a non-draft update (the whole merged document when it enters a visible status)
147
+ * @param draftDocumentSchema - The draft schema: validates the merged document of a draft
148
+ * @returns The callable logic (exported for unit tests)
149
+ *
150
+ * @version 0.2.0
140
151
  * @since 0.0.1
141
152
  * @author AMBROISE PARK Consulting
142
153
  */
143
- function updateEntityLogicFactory(
154
+ export function updateEntityLogicFactory(
144
155
  collection: string,
145
- documentSchema: v.GenericSchema
156
+ documentSchema: v.GenericSchema,
157
+ draftDocumentSchema: v.GenericSchema
146
158
  ) {
147
159
  return async function updateEntityLogic(
148
160
  data: UpdateEntityRequest,
@@ -209,18 +221,22 @@ function updateEntityLogicFactory(
209
221
 
210
222
  // Check if the document exists
211
223
  const doc = await docRef.get();
212
- if (!doc.exists) {
224
+ const storedData = doc.data();
225
+ if (!doc.exists || storedData === undefined) {
213
226
  throw new DoNotDevError('Entity not found', 'not-found');
214
227
  }
215
228
 
216
229
  // Get the current data and merge with the update payload.
217
230
  // Note: simple spread merge — concurrent partial updates use last-write-wins, no conflict detection.
218
- const currentData = transformFirestoreData(doc.data());
231
+ const currentData = transformFirestoreData(storedData);
219
232
  const mergedData = { ...currentData, ...payload };
220
233
 
221
- // Determine resulting status (default to draft if not set)
222
- const resultingStatus = mergedData.status ?? DEFAULT_STATUS_VALUE;
223
- const isDraft = resultingStatus === 'draft';
234
+ // CRUD update rules (core/schemas crud/update) on the stored row, as on the client.
235
+ const prepared = prepareUpdate(
236
+ { draft: draftDocumentSchema, update: documentSchema },
237
+ { id, patch: payload, stored: currentData }
238
+ );
239
+ const isDraft = prepared.schemaKey === 'draft';
224
240
 
225
241
  // Check unique keys if schema has metadata with uniqueKeys
226
242
  // Only checks fields that are being updated
@@ -240,17 +256,14 @@ function updateEntityLogicFactory(
240
256
  );
241
257
  }
242
258
 
243
- // Validate the merged document against the schema
244
- // Skip validation for drafts - required fields can be incomplete
245
- if (!isDraft) {
246
- validateDocument(mergedData, documentSchema);
247
- }
259
+ // The rules' `written` (parsed sent keys), never the raw payload.
260
+ const written = writtenOf(prepared, collection, 'update');
248
261
 
249
262
  // Normalize unique key fields to lowercase for case-insensitive storage
250
263
  const normalizedPayload =
251
264
  uniqueKeys && uniqueKeys.length > 0
252
- ? normalizePayloadForUniqueKeys(payload, uniqueKeys)
253
- : payload;
265
+ ? normalizePayloadForUniqueKeys(written, uniqueKeys)
266
+ : written;
254
267
 
255
268
  // Prepare the update data for Firestore and add metadata
256
269
  const updateData = {
@@ -289,7 +302,8 @@ function updateEntityLogicFactory(
289
302
  /**
290
303
  * Generic function to update entities in any Firestore collection
291
304
  * @param collection - The Firestore collection name
292
- * @param documentSchema - The Valibot schema for document validation
305
+ * @param documentSchema - The update schema (`createSchemas(entity).update`): validates what a non-draft update writes
306
+ * @param draftDocumentSchema - The draft schema (`createSchemas(entity).draft`): validates the resulting document of a draft
293
307
  * @param requiredRole - Minimum role required for this operation
294
308
  * @param customSchema - Optional custom request schema
295
309
  * @returns Firebase callable function
@@ -298,6 +312,8 @@ export const updateEntity = (
298
312
  collection: string,
299
313
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
300
314
  documentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
315
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
316
+ draftDocumentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
301
317
  requiredRole: UserRole,
302
318
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
303
319
  customSchema?: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>
@@ -315,7 +331,7 @@ export const updateEntity = (
315
331
  CRUD_CONFIG,
316
332
  requestSchema,
317
333
  'update_entity',
318
- updateEntityLogicFactory(collection, documentSchema),
334
+ updateEntityLogicFactory(collection, documentSchema, draftDocumentSchema),
319
335
  requiredRole
320
336
  );
321
337
  };
@@ -100,6 +100,7 @@ export function createCrudFunctions(
100
100
  functions[`${prefix}update_${col}`] = updateEntity(
101
101
  col,
102
102
  schemas.update,
103
+ schemas.draft,
103
104
  access.update
104
105
  );
105
106
  functions[`${prefix}delete_${col}`] = deleteEntity(col, access.delete);
@@ -15,8 +15,10 @@ import { describe, it, expect, vi } from 'vitest';
15
15
  import { BulkCollisionError } from '@donotdev/core/server';
16
16
  import { DoNotDevError } from '@donotdev/core/server';
17
17
  import { DEFAULT_STATUS_VALUE } from '@donotdev/core/server';
18
+ import { createSchemas } from '@donotdev/core/server';
18
19
 
19
20
  import { executeBulk } from '../crud/bulkCore.js';
21
+ import { contactEntity } from '@dndev/test-entities';
20
22
 
21
23
  // ---------------------------------------------------------------------------
22
24
  // Fixtures
@@ -32,6 +34,11 @@ const ACCESS = {
32
34
  delete: 'user' as const,
33
35
  };
34
36
 
37
+ /** Stored rows of the mock store: every updated id exists, published, unless listed. */
38
+ let storedRows: Record<string, Record<string, unknown>> = {};
39
+ const readStored = async (ids: readonly string[]) =>
40
+ new Map(ids.map((id) => [id, storedRows[id] ?? { status: 'available' }]));
41
+
35
42
  /** Default response-shape returned by the mock transact. */
36
43
  function okResponse(prepared: {
37
44
  inserts: Array<{ id: string; row: Record<string, unknown> }>;
@@ -60,6 +67,7 @@ describe('executeBulk (shared CRUD core)', () => {
60
67
  createSchema,
61
68
  updateSchema,
62
69
  access: ACCESS,
70
+ readStored,
63
71
  uid: 'u1',
64
72
  userRole: 'user',
65
73
  transact,
@@ -85,6 +93,7 @@ describe('executeBulk (shared CRUD core)', () => {
85
93
  createSchema,
86
94
  updateSchema,
87
95
  access: ACCESS,
96
+ readStored,
88
97
  uid: 'u1',
89
98
  userRole: 'user',
90
99
  transact,
@@ -114,6 +123,7 @@ describe('executeBulk (shared CRUD core)', () => {
114
123
  createSchema,
115
124
  updateSchema,
116
125
  access: ACCESS,
126
+ readStored,
117
127
  uid: 'u1',
118
128
  userRole: 'user',
119
129
  transact,
@@ -138,6 +148,7 @@ describe('executeBulk (shared CRUD core)', () => {
138
148
  createSchema,
139
149
  updateSchema,
140
150
  access: ACCESS,
151
+ readStored,
141
152
  uid: 'u1',
142
153
  userRole: 'user',
143
154
  transact,
@@ -159,6 +170,7 @@ describe('executeBulk (shared CRUD core)', () => {
159
170
  createSchema,
160
171
  updateSchema,
161
172
  access: { ...ACCESS, delete: 'admin' },
173
+ readStored,
162
174
  uid: 'u1',
163
175
  userRole: 'user',
164
176
  transact,
@@ -181,6 +193,7 @@ describe('executeBulk (shared CRUD core)', () => {
181
193
  createSchema,
182
194
  updateSchema,
183
195
  access: { read: 'user' }, // no create role configured
196
+ readStored,
184
197
  uid: 'u1',
185
198
  userRole: 'user',
186
199
  transact,
@@ -204,6 +217,7 @@ describe('executeBulk (shared CRUD core)', () => {
204
217
  createSchema,
205
218
  updateSchema,
206
219
  access: { update: 'user' }, // no create/delete roles configured — fine
220
+ readStored,
207
221
  uid: 'u1',
208
222
  userRole: 'user',
209
223
  transact,
@@ -225,6 +239,7 @@ describe('executeBulk (shared CRUD core)', () => {
225
239
  createSchema,
226
240
  updateSchema,
227
241
  access: ACCESS,
242
+ readStored,
228
243
  uid: 'u1',
229
244
  userRole: 'user',
230
245
  transact,
@@ -249,6 +264,7 @@ describe('executeBulk (shared CRUD core)', () => {
249
264
  createSchema,
250
265
  updateSchema,
251
266
  access: ACCESS,
267
+ readStored,
252
268
  uid: 'u1',
253
269
  userRole: 'user',
254
270
  transact,
@@ -261,6 +277,173 @@ describe('executeBulk (shared CRUD core)', () => {
261
277
  expect(transact).not.toHaveBeenCalled();
262
278
  });
263
279
 
280
+ it('validates updates with the entity schemas: draft patch → draft schema, other → update schema (with the id)', async () => {
281
+ const schemas = createSchemas(contactEntity);
282
+ const run = (patch: Record<string, unknown>) =>
283
+ executeBulk({
284
+ collection: 'contacts',
285
+ ops: { updates: [{ id: 'c1', patch }] },
286
+ createSchema: schemas.create,
287
+ draftCreateSchema: schemas.draft,
288
+ updateSchema: schemas.update,
289
+ access: ACCESS,
290
+ readStored,
291
+ uid: 'u1',
292
+ userRole: 'user',
293
+ transact: async (prepared) => okResponse(prepared),
294
+ });
295
+ await expect(run({ name: 'Ana' })).resolves.toMatchObject({ updatedIds: ['c1'] });
296
+ await expect(run({ status: 'draft', name: null })).resolves.toMatchObject({ updatedIds: ['c1'] });
297
+ for (const patch of [{ name: null }, { name: '' }, { status: 'draft', phone: 'TOTO' }]) {
298
+ await expect(run(patch)).rejects.toMatchObject({ code: 'invalid-argument' });
299
+ }
300
+ });
301
+
302
+ it('stores the parse output: unknown keys dropped from inserts and patches', async () => {
303
+ const transact = vi.fn(okResponse);
304
+ await executeBulk({
305
+ collection: 'events',
306
+ ops: {
307
+ inserts: [{ name: 'Alice', role: 'admin' }],
308
+ updates: [{ id: 'u1', patch: { name: 'Bob', createdById: 'evil' } }],
309
+ },
310
+ createSchema,
311
+ updateSchema,
312
+ access: ACCESS,
313
+ readStored,
314
+ uid: 'u1',
315
+ userRole: 'user',
316
+ transact,
317
+ });
318
+ const prepared = transact.mock.calls[0]![0];
319
+ expect(prepared.inserts[0]!.row).toEqual({ name: 'Alice', status: DEFAULT_STATUS_VALUE });
320
+ expect(prepared.updates[0]!.patch).toEqual({ name: 'Bob' });
321
+ });
322
+
323
+ it('keeps a client-supplied insert id (pre-minted, referenced by other rows) when the target mints', async () => {
324
+ const schemas = createSchemas(contactEntity);
325
+ const transact = vi.fn(okResponse);
326
+ await executeBulk({
327
+ collection: 'lines',
328
+ ops: { inserts: [{ id: 'line-1', name: 'A' }, { name: 'B' }] },
329
+ createSchema: schemas.create,
330
+ updateSchema: schemas.update,
331
+ access: ACCESS,
332
+ readStored,
333
+ uid: 'u1',
334
+ userRole: 'user',
335
+ transact,
336
+ });
337
+ const prepared = transact.mock.calls[0]![0];
338
+ expect(prepared.inserts[0]).toMatchObject({ id: 'line-1', row: { id: 'line-1', name: 'A' } });
339
+ expect(prepared.inserts[1]!.id).toBe('');
340
+ expect(prepared.inserts[1]!.row).not.toHaveProperty('id');
341
+ });
342
+
343
+ it('with mintInsertId the minted id wins over a client id', async () => {
344
+ const transact = vi.fn(okResponse);
345
+ await executeBulk({
346
+ collection: 'events',
347
+ ops: { inserts: [{ id: 'client-1', name: 'A' }] },
348
+ createSchema,
349
+ updateSchema,
350
+ access: ACCESS,
351
+ readStored,
352
+ uid: 'u1',
353
+ userRole: 'user',
354
+ mintInsertId: () => 'minted-1',
355
+ transact,
356
+ });
357
+ const prepared = transact.mock.calls[0]![0];
358
+ expect(prepared.inserts[0]!.id).toBe('minted-1');
359
+ expect(prepared.inserts[0]!.row).not.toHaveProperty('id');
360
+ });
361
+
362
+ it('update schema from the resulting status (patch ?? stored): a stored draft edit stays a draft write', async () => {
363
+ const schemas = createSchemas(contactEntity);
364
+ const transact = vi.fn(okResponse);
365
+ const run = (patch: Record<string, unknown>) =>
366
+ executeBulk({
367
+ collection: 'contacts',
368
+ ops: { updates: [{ id: 'c1', patch }] },
369
+ createSchema: schemas.create,
370
+ draftCreateSchema: schemas.draft,
371
+ updateSchema: schemas.update,
372
+ access: ACCESS,
373
+ readStored,
374
+ uid: 'u1',
375
+ userRole: 'user',
376
+ transact,
377
+ });
378
+ // Client form edit of a stored draft by a viewer who cannot edit status
379
+ storedRows = { c1: { id: 'c1', name: 'Ana', status: 'draft' } };
380
+ await expect(run({ name: null })).resolves.toMatchObject({ updatedIds: ['c1'] });
381
+ // Publishing through a status-only patch: the whole stored row is checked
382
+ storedRows = { c1: { id: 'c1', name: null, status: 'draft' } };
383
+ await expect(run({ status: 'available' })).rejects.toMatchObject({ code: 'invalid-argument', message: expect.stringContaining('updates[0]') });
384
+ storedRows = { c1: { id: 'c1', status: 'draft' } };
385
+ await expect(run({ status: 'available' })).rejects.toMatchObject({ code: 'invalid-argument' });
386
+ // Soft-deleting a draft stays relaxed
387
+ storedRows = { c1: { id: 'c1', name: null, status: 'draft' } };
388
+ await expect(run({ status: 'deleted' })).resolves.toMatchObject({ updatedIds: ['c1'] });
389
+ // Filled in: published, only the sent keys written
390
+ transact.mockClear();
391
+ storedRows = { c1: { id: 'c1', name: 'Ana', status: 'draft' } };
392
+ await run({ status: 'available' });
393
+ expect(transact.mock.calls[0]![0].updates[0]!.patch).toEqual({ status: 'available' });
394
+ storedRows = {};
395
+ });
396
+
397
+ it('updates without readStored are rejected (internal), no transact', async () => {
398
+ const transact = vi.fn(okResponse);
399
+ await expect(
400
+ executeBulk({
401
+ collection: 'events',
402
+ ops: { updates: [{ id: 'e1', patch: { name: 'x' } }] },
403
+ createSchema,
404
+ updateSchema,
405
+ access: ACCESS,
406
+ uid: 'u1',
407
+ userRole: 'user',
408
+ transact,
409
+ })
410
+ ).rejects.toMatchObject({ code: 'internal', message: expect.stringContaining('readStored') });
411
+ expect(transact).not.toHaveBeenCalled();
412
+ });
413
+
414
+ it('inserts and deletes need no readStored', async () => {
415
+ await expect(
416
+ executeBulk({
417
+ collection: 'events',
418
+ ops: { inserts: [{ name: 'a' }], deletes: ['e9'] },
419
+ createSchema,
420
+ updateSchema,
421
+ access: ACCESS,
422
+ uid: 'u1',
423
+ userRole: 'user',
424
+ transact: async (prepared) => okResponse(prepared),
425
+ })
426
+ ).resolves.toMatchObject({ deletedIds: ['e9'] });
427
+ });
428
+
429
+ it('an updated id with no stored row is rejected (not-found), no transact', async () => {
430
+ const transact = vi.fn(okResponse);
431
+ await expect(
432
+ executeBulk({
433
+ collection: 'events',
434
+ ops: { updates: [{ id: 'gone', patch: { name: 'x' } }] },
435
+ createSchema,
436
+ updateSchema,
437
+ access: ACCESS,
438
+ readStored: async () => new Map(),
439
+ uid: 'u1',
440
+ userRole: 'user',
441
+ transact,
442
+ })
443
+ ).rejects.toMatchObject({ code: 'not-found', message: expect.stringContaining('updates[0]') });
444
+ expect(transact).not.toHaveBeenCalled();
445
+ });
446
+
264
447
  it('wire-schema failure throws invalid-argument without calling transact', async () => {
265
448
  const transact = vi.fn();
266
449
 
@@ -272,6 +455,7 @@ describe('executeBulk (shared CRUD core)', () => {
272
455
  createSchema,
273
456
  updateSchema,
274
457
  access: ACCESS,
458
+ readStored,
275
459
  uid: 'u1',
276
460
  userRole: 'user',
277
461
  transact,
@@ -299,6 +483,7 @@ describe('executeBulk (shared CRUD core)', () => {
299
483
  createSchema,
300
484
  updateSchema,
301
485
  access: ACCESS,
486
+ readStored,
302
487
  uid: 'user-1',
303
488
  userRole: 'user',
304
489
  mintInsertId: () => `mint-${++mintCounter}`,
@@ -364,6 +549,7 @@ describe('executeBulk (shared CRUD core)', () => {
364
549
  createSchema,
365
550
  updateSchema,
366
551
  access: ACCESS,
552
+ readStored,
367
553
  uid: 'user-1',
368
554
  userRole: 'user',
369
555
  transact,
@@ -391,6 +577,7 @@ describe('executeBulk (shared CRUD core)', () => {
391
577
  createSchema,
392
578
  updateSchema,
393
579
  access: ACCESS,
580
+ readStored,
394
581
  uid: 'u1',
395
582
  userRole: 'user',
396
583
  transact,
@@ -415,6 +602,7 @@ describe('executeBulk (shared CRUD core)', () => {
415
602
  createSchema,
416
603
  updateSchema,
417
604
  access: ACCESS,
605
+ readStored,
418
606
  uid: 'u1',
419
607
  userRole: 'user',
420
608
  transact,
@@ -440,6 +628,7 @@ describe('executeBulk (shared CRUD core)', () => {
440
628
  createSchema,
441
629
  updateSchema,
442
630
  access: ACCESS,
631
+ readStored,
443
632
  uid: 'u1',
444
633
  userRole: 'user',
445
634
  transact,
@@ -461,6 +650,7 @@ describe('executeBulk (shared CRUD core)', () => {
461
650
  createSchema,
462
651
  updateSchema,
463
652
  access: ACCESS,
653
+ readStored,
464
654
  uid: 'u1',
465
655
  userRole: 'user',
466
656
  transact,
@@ -479,6 +669,7 @@ describe('executeBulk (shared CRUD core)', () => {
479
669
  createSchema,
480
670
  updateSchema,
481
671
  access: ACCESS,
672
+ readStored,
482
673
  uid: 'u1',
483
674
  userRole: 'user',
484
675
  transact,
@@ -0,0 +1,117 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
+
3
+ const { getUser, setCustomUserClaims, getUserById, updateUserById } = vi.hoisted(() => ({
4
+ getUser: vi.fn(),
5
+ setCustomUserClaims: vi.fn(),
6
+ getUserById: vi.fn(),
7
+ updateUserById: vi.fn(),
8
+ }));
9
+
10
+ vi.mock('@donotdev/firebase/server', () => ({
11
+ getFirebaseAdminAuth: () => ({ getUser, setCustomUserClaims }),
12
+ }));
13
+ vi.mock('../../firebase/baseFunction.js', () => ({
14
+ createBaseFunction: (_config: unknown, _schema: unknown, _name: string, handler: unknown) => handler,
15
+ }));
16
+ vi.mock('../../supabase/baseFunction.js', () => ({
17
+ createSupabaseHandler: (_name: string, _schema: unknown, handler: unknown) => handler,
18
+ }));
19
+
20
+ import { removeCustomClaims } from '../../firebase/auth/removeCustomClaims.js';
21
+ import { createRemoveCustomClaims } from '../../supabase/auth/removeCustomClaims.js';
22
+
23
+ // Base wrappers are mocked to expose only the authenticated business logic.
24
+ type Handler = (data: { claimsToRemove: string[] }, context: unknown) => Promise<unknown>;
25
+
26
+ const subscription = {
27
+ tier: 'member',
28
+ status: 'active',
29
+ subscriptionEnd: null,
30
+ updatedAt: '2026-06-01T00:00:00.000Z',
31
+ };
32
+ const paidSubscription = {
33
+ ...subscription,
34
+ tier: 'premium',
35
+ subscriptionId: 'sub_paid',
36
+ customerId: 'cus_paid',
37
+ cancelAtPeriodEnd: false,
38
+ };
39
+ const existingClaims = { subscription, role: 'user', locale: 'en', theme: 'dark' };
40
+ const protectedKeys = [
41
+ 'admin', 'isAdmin', 'isSuper', 'isSuperAdmin', 'role', 'roles',
42
+ 'permissions', 'superuser', 'moderator', 'staff', 'elevated',
43
+ 'plan', 'tier', 'subscription', 'provider', 'providers', 'sub', 'iss', 'aud',
44
+ ];
45
+
46
+ beforeEach(() => {
47
+ vi.clearAllMocks();
48
+ getUser.mockResolvedValue({ customClaims: existingClaims });
49
+ setCustomUserClaims.mockResolvedValue(undefined);
50
+ getUserById.mockResolvedValue({ data: { user: { app_metadata: existingClaims } }, error: null });
51
+ updateUserById.mockResolvedValue({ error: null });
52
+ });
53
+
54
+ for (const provider of ['firebase', 'supabase'] as const) {
55
+ describe(`${provider} self-service claim removal`, () => {
56
+ const create = () => (provider === 'firebase'
57
+ ? removeCustomClaims()
58
+ : createRemoveCustomClaims()) as unknown as Handler;
59
+ const context = {
60
+ uid: 'user-1',
61
+ supabaseAdmin: { auth: { admin: { getUserById, updateUserById } } },
62
+ };
63
+
64
+ it.each(protectedKeys)('rejects protected %s removal before accessing the provider', async (key) => {
65
+ await expect(create()({ claimsToRemove: ['locale', key] }, context))
66
+ .rejects.toThrow(`Protected claims cannot be removed: ${key}`);
67
+ expect(getUser).not.toHaveBeenCalled();
68
+ expect(getUserById).not.toHaveBeenCalled();
69
+ expect(setCustomUserClaims).not.toHaveBeenCalled();
70
+ expect(updateUserById).not.toHaveBeenCalled();
71
+ expect(existingClaims.locale).toBe('en');
72
+ });
73
+
74
+ it.each([subscription, paidSubscription])(
75
+ 'preserves canonical subscription and unrelated metadata when removing safe keys',
76
+ async (canonicalSubscription) => {
77
+ const claims = { ...existingClaims, subscription: canonicalSubscription };
78
+ getUser.mockResolvedValue({ customClaims: claims });
79
+ getUserById.mockResolvedValue({ data: { user: { app_metadata: claims } }, error: null });
80
+ const updatedClaims = { subscription: canonicalSubscription, role: 'user' };
81
+
82
+ await expect(create()({ claimsToRemove: ['locale', 'theme', 'missing'] }, context))
83
+ .resolves.toEqual({ success: true, customClaims: updatedClaims });
84
+ if (provider === 'firebase') {
85
+ expect(setCustomUserClaims).toHaveBeenCalledExactlyOnceWith('user-1', updatedClaims);
86
+ } else {
87
+ expect(updateUserById).toHaveBeenCalledExactlyOnceWith('user-1', {
88
+ app_metadata: { locale: null, theme: null, missing: null },
89
+ });
90
+ }
91
+ expect(claims).toEqual({ ...existingClaims, subscription: canonicalSubscription });
92
+ }
93
+ );
94
+
95
+ it.runIf(provider === 'supabase')('actually deletes safe keys without replaying a stale subscription', async () => {
96
+ const revoked = { ...subscription, tier: 'free', status: 'canceled' };
97
+ const stored: Record<string, unknown> = { ...existingClaims, subscription: revoked };
98
+ // Mirror Supabase Auth UpdateAppMetaData: merge values, delete null keys.
99
+ updateUserById.mockImplementation(async (_uid, { app_metadata }) => {
100
+ for (const [key, value] of Object.entries(app_metadata)) {
101
+ if (value === null) delete stored[key];
102
+ else stored[key] = value;
103
+ }
104
+ return { error: null };
105
+ });
106
+ await create()({ claimsToRemove: ['locale', 'theme'] }, context);
107
+ expect(stored).toEqual({ subscription: revoked, role: 'user' });
108
+ });
109
+
110
+ it('keeps safe removal working when the user has no claims', async () => {
111
+ getUser.mockResolvedValue({});
112
+ getUserById.mockResolvedValue({ data: { user: {} }, error: null });
113
+ await expect(create()({ claimsToRemove: ['locale'] }, context))
114
+ .resolves.toEqual({ success: true, customClaims: {} });
115
+ });
116
+ });
117
+ }