@donotdev/functions 0.2.3 → 0.3.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/lib/chunks/{chunk-6NXIK35R.js → chunk-522YXGDA.js} +2 -2
- package/lib/chunks/chunk-7ODXXXES.js +151 -0
- package/lib/chunks/{chunk-F3WBFWPO.js.map → chunk-7ODXXXES.js.map} +3 -3
- package/lib/chunks/chunk-CP3NNKO5.js +22 -0
- package/lib/chunks/chunk-CP3NNKO5.js.map +7 -0
- package/lib/chunks/{chunk-GDIUOJMD.js → chunk-CVYSXC27.js} +2 -2
- package/lib/chunks/{chunk-UH445BGK.js → chunk-HZM5X5A7.js} +2 -2
- package/lib/chunks/chunk-ICNQCRLV.js +22 -0
- package/lib/chunks/chunk-ICNQCRLV.js.map +7 -0
- package/lib/chunks/chunk-OAZ2JYSD.js +22 -0
- package/lib/chunks/chunk-OAZ2JYSD.js.map +7 -0
- package/lib/chunks/{chunk-QXIOO2RL.js → chunk-OKRR7ST5.js} +2 -2
- package/lib/chunks/chunk-PDBNKSBQ.js +22 -0
- package/lib/chunks/chunk-PDBNKSBQ.js.map +7 -0
- package/lib/chunks/chunk-TJPJXJEK.js +22 -0
- package/lib/chunks/{chunk-EZKRLLSQ.js.map → chunk-TJPJXJEK.js.map} +1 -1
- package/lib/chunks/{monitoring-LXNVBD3G.js → monitoring-UCBNPPW2.js} +2 -2
- package/lib/chunks/{rateLimiter-GG5LPWXJ.js → rateLimiter-XKECWM33.js} +2 -2
- package/lib/chunks/{server-NODQAE3F.js → server-24XGDDO3.js} +2 -2
- package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
- package/lib/firebase/crud/create.d.ts +22 -1
- package/lib/firebase/crud/update.d.ts +27 -3
- package/lib/firebase/index.js +1 -1
- package/lib/firebase/index.js.map +3 -3
- package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -8
- package/lib/shared/billing/index.d.ts +2 -0
- package/lib/shared/billing/verifyOrderCheckout.d.ts +53 -0
- package/lib/shared/crud/bulkCore.d.ts +38 -10
- package/lib/shared/crud/index.d.ts +1 -0
- package/lib/shared/crud/written.d.ts +21 -0
- package/lib/shared/index.d.ts +0 -1
- package/lib/shared/index.js +1 -1
- package/lib/shared/utils.d.ts +0 -9
- package/lib/supabase/crud/bulk.d.ts +7 -0
- package/lib/supabase/crud/create.d.ts +5 -1
- package/lib/supabase/crud/entityStore.d.ts +54 -14
- package/lib/supabase/crud/update.d.ts +7 -2
- package/lib/supabase/index.d.ts +4 -0
- package/lib/supabase/index.js +1 -1
- package/lib/supabase/index.js.map +3 -3
- package/lib/vercel/api/crud/create.d.ts +6 -1
- package/lib/vercel/api/crud/update.d.ts +8 -1
- package/lib/vercel/api/index.js +1 -1
- package/package.json +3 -3
- package/src/firebase/auth/removeCustomClaims.ts +31 -1
- package/src/firebase/auth/setCustomClaims.ts +3 -0
- package/src/firebase/crud/__tests__/bulk.test.ts +50 -1
- package/src/firebase/crud/__tests__/create.test.ts +64 -0
- package/src/firebase/crud/__tests__/update.test.ts +97 -0
- package/src/firebase/crud/aggregate.ts +10 -21
- package/src/firebase/crud/bulk.ts +23 -10
- package/src/firebase/crud/create.ts +19 -18
- package/src/firebase/crud/get.ts +3 -12
- package/src/firebase/crud/list.ts +5 -4
- package/src/firebase/crud/update.ts +35 -19
- package/src/firebase/registerCrudFunctions.ts +1 -0
- package/src/shared/__tests__/bulkCore.test.ts +191 -0
- package/src/shared/__tests__/removeCustomClaims.test.ts +117 -0
- package/src/shared/__tests__/setCustomClaims.test.ts +103 -0
- package/src/shared/__tests__/utils.test.ts +0 -30
- package/src/shared/billing/__tests__/updateUserSubscription.test.ts +139 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.exports.test.ts +47 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.supabase.integration.test.ts +107 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.test.ts +233 -0
- package/src/shared/billing/helpers/updateUserSubscription.ts +10 -14
- package/src/shared/billing/index.ts +2 -0
- package/src/shared/billing/verifyOrderCheckout.ts +142 -0
- package/src/shared/crud/bulkCore.ts +110 -81
- package/src/shared/crud/index.ts +1 -0
- package/src/shared/crud/written.ts +56 -0
- package/src/shared/index.d.ts +0 -9
- package/src/shared/index.ts +0 -1
- package/src/shared/utils.ts +0 -43
- package/src/supabase/__tests__/bulk.test.ts +60 -2
- package/src/supabase/__tests__/create.test.ts +86 -0
- package/src/supabase/__tests__/entityStore.test.ts +91 -25
- package/src/supabase/__tests__/update.test.ts +107 -0
- package/src/supabase/auth/removeCustomClaims.ts +7 -2
- package/src/supabase/auth/setCustomClaims.ts +4 -2
- package/src/supabase/crud/bulk.ts +47 -0
- package/src/supabase/crud/create.ts +14 -24
- package/src/supabase/crud/entityStore.ts +106 -17
- package/src/supabase/crud/get.ts +3 -12
- package/src/supabase/crud/list.ts +5 -4
- package/src/supabase/crud/update.ts +20 -18
- package/src/supabase/index.ts +7 -0
- package/src/supabase/registerCrudFunctions.ts +1 -0
- package/src/vercel/__tests__/bulk.test.ts +16 -8
- package/src/vercel/api/crud/bulk.ts +27 -4
- package/src/vercel/api/crud/create.ts +17 -19
- package/src/vercel/api/crud/get.ts +5 -6
- package/src/vercel/api/crud/list.ts +4 -5
- package/src/vercel/api/crud/update.ts +20 -18
- package/lib/chunks/chunk-EZKRLLSQ.js +0 -22
- package/lib/chunks/chunk-F3PHE627.js +0 -22
- package/lib/chunks/chunk-F3PHE627.js.map +0 -7
- package/lib/chunks/chunk-F3WBFWPO.js +0 -151
- package/lib/chunks/chunk-G5DRV3DH.js +0 -22
- package/lib/chunks/chunk-G5DRV3DH.js.map +0 -7
- package/lib/chunks/chunk-Q2WLRFOE.js +0 -22
- package/lib/chunks/chunk-Q2WLRFOE.js.map +0 -7
- package/lib/chunks/chunk-W74UL7AY.js +0 -22
- package/lib/chunks/chunk-W74UL7AY.js.map +0 -7
- package/lib/shared/schema.d.ts +0 -56
- package/src/shared/__tests__/schema.test.ts +0 -219
- package/src/shared/schema.ts +0 -188
- /package/lib/chunks/{chunk-6NXIK35R.js.map → chunk-522YXGDA.js.map} +0 -0
- /package/lib/chunks/{chunk-GDIUOJMD.js.map → chunk-CVYSXC27.js.map} +0 -0
- /package/lib/chunks/{chunk-UH445BGK.js.map → chunk-HZM5X5A7.js.map} +0 -0
- /package/lib/chunks/{chunk-QXIOO2RL.js.map → chunk-OKRR7ST5.js.map} +0 -0
- /package/lib/chunks/{monitoring-LXNVBD3G.js.map → monitoring-UCBNPPW2.js.map} +0 -0
- /package/lib/chunks/{rateLimiter-GG5LPWXJ.js.map → rateLimiter-XKECWM33.js.map} +0 -0
- /package/lib/chunks/{server-NODQAE3F.js.map → server-24XGDDO3.js.map} +0 -0
|
@@ -9,11 +9,16 @@
|
|
|
9
9
|
* @author AMBROISE PARK Consulting
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
+
import * as v from 'valibot';
|
|
13
|
+
|
|
14
|
+
import { SubscriptionClaimsSchema } from '@donotdev/core/server';
|
|
12
15
|
import type { BillingAuthProvider, SubscriptionUpdate } from '@donotdev/core/server';
|
|
13
16
|
|
|
14
17
|
/**
|
|
15
18
|
* Platform-agnostic subscription update using dependency injection
|
|
16
19
|
* Works on Firebase Functions, Vercel, AWS Lambda, etc.
|
|
20
|
+
* Validates canonical auth claims; one-time payments may have no billing customer.
|
|
21
|
+
* Billing identifiers are preserved when supplied, never fabricated from a user ID.
|
|
17
22
|
*
|
|
18
23
|
* @version 0.1.0
|
|
19
24
|
* @since 0.0.1
|
|
@@ -31,26 +36,17 @@ export async function updateUserSubscription(
|
|
|
31
36
|
throw new Error('Invalid subscription data: missing tier or status');
|
|
32
37
|
}
|
|
33
38
|
|
|
34
|
-
|
|
35
|
-
// Stripe customer ID, which makes future Stripe API calls unreliable.
|
|
36
|
-
if (!subscriptionData.customerId) {
|
|
37
|
-
console.warn(
|
|
38
|
-
`[updateUserSubscription] customerId is undefined for user ${userId}. ` +
|
|
39
|
-
`Falling back to userId. This may cause issues with Stripe API calls.`
|
|
40
|
-
);
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
const subscriptionClaims = {
|
|
39
|
+
const subscriptionClaims = v.parse(SubscriptionClaimsSchema, {
|
|
44
40
|
tier: subscriptionData.tier,
|
|
45
|
-
subscriptionId: subscriptionData.subscriptionId
|
|
46
|
-
customerId: subscriptionData.customerId
|
|
41
|
+
subscriptionId: subscriptionData.subscriptionId ?? null,
|
|
42
|
+
customerId: subscriptionData.customerId ?? null,
|
|
47
43
|
status: subscriptionData.status,
|
|
48
44
|
// Keep as ISO string - no conversion needed
|
|
49
45
|
subscriptionEnd: subscriptionData.subscriptionEnd,
|
|
50
|
-
cancelAtPeriodEnd: subscriptionData.cancelAtPeriodEnd
|
|
46
|
+
cancelAtPeriodEnd: subscriptionData.cancelAtPeriodEnd ?? false,
|
|
51
47
|
updatedAt: new Date().toISOString(),
|
|
52
48
|
isDefault: false,
|
|
53
|
-
};
|
|
49
|
+
});
|
|
54
50
|
|
|
55
51
|
const updatedClaims = {
|
|
56
52
|
...currentClaims,
|
|
@@ -10,6 +10,8 @@
|
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
12
|
export * from './createCheckout.js';
|
|
13
|
+
/** Read-only order verification and its separate retrieval/binding dependencies. */
|
|
14
|
+
export * from './verifyOrderCheckout.js';
|
|
13
15
|
export * from './helpers/index.js';
|
|
14
16
|
export * from './webhookHandler.js';
|
|
15
17
|
export * from './idempotency.js';
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read-only StripeOrder verification for an authenticated return-page handler.
|
|
3
|
+
* Persisted app binding is mandatory; Stripe metadata is corroboration, not authority.
|
|
4
|
+
*/
|
|
5
|
+
import type Stripe from 'stripe';
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
validateVerifyOrderCheckoutRequest,
|
|
9
|
+
validateVerifyOrderCheckoutResult,
|
|
10
|
+
} from '@donotdev/core/server';
|
|
11
|
+
import type {
|
|
12
|
+
StripeBackConfig,
|
|
13
|
+
VerifyOrderCheckoutRequest,
|
|
14
|
+
VerifyOrderCheckoutResult,
|
|
15
|
+
} from '@donotdev/core/server';
|
|
16
|
+
|
|
17
|
+
import { logger } from '../logger.js';
|
|
18
|
+
import { ORDER_ID_METADATA_KEY } from './orderWebhook.js';
|
|
19
|
+
|
|
20
|
+
/** App-owned persisted association, read from authoritative storage (never request metadata). */
|
|
21
|
+
export interface OrderCheckoutBinding {
|
|
22
|
+
orderId: string;
|
|
23
|
+
userId: string;
|
|
24
|
+
sessionId: string;
|
|
25
|
+
billingConfigKey: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Read dependencies only. Separate from StripeSessionProvider so existing checkout
|
|
30
|
+
* providers remain compatible. userId must come from verified handler context.
|
|
31
|
+
*/
|
|
32
|
+
export interface VerifyOrderCheckoutDependencies {
|
|
33
|
+
userId: string;
|
|
34
|
+
billingConfig: StripeBackConfig;
|
|
35
|
+
/** Retrieve from Stripe using server credentials; no browser-supplied session objects. */
|
|
36
|
+
retrieveStripeSession(sessionId: string): Promise<Pick<
|
|
37
|
+
Stripe.Checkout.Session,
|
|
38
|
+
'id' | 'mode' | 'status' | 'payment_status' | 'metadata'
|
|
39
|
+
>>;
|
|
40
|
+
/**
|
|
41
|
+
* Read the persisted order/session binding, scoped to the authenticated owner
|
|
42
|
+
* and config. Return absence if not authorized/found; never infer it from Stripe.
|
|
43
|
+
* The algorithm independently checks every returned binding field.
|
|
44
|
+
*/
|
|
45
|
+
resolveOrderBinding(
|
|
46
|
+
request: VerifyOrderCheckoutRequest & { userId: string }
|
|
47
|
+
): Promise<OrderCheckoutBinding | null | undefined>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Verify an owner's StripeOrder session against server config and persisted binding.
|
|
52
|
+
* All validation, authorization and dependency failures expose the same safe error.
|
|
53
|
+
* Server diagnostics contain fixed stage/category labels only, never dependency
|
|
54
|
+
* errors or request/customer data. Logging failure cannot replace the public error.
|
|
55
|
+
* No writes, checkout hooks or fulfillment hooks run. A successful read reports
|
|
56
|
+
* payment state only: complete/unpaid is pending; paid/no_payment_required does not
|
|
57
|
+
* prove onOrderPaid has run. Existing webhook fulfillment remains authoritative.
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* ```typescript
|
|
61
|
+
* // Inside createSupabaseHandler(..., v.unknown(), (data, ctx) => ...)
|
|
62
|
+
* // The algorithm performs mandatory request validation itself.
|
|
63
|
+
* return verifyOrderCheckoutAlgorithm(data, {
|
|
64
|
+
* userId: ctx.uid,
|
|
65
|
+
* billingConfig,
|
|
66
|
+
* retrieveStripeSession: (id) => stripe.checkout.sessions.retrieve(id),
|
|
67
|
+
* resolveOrderBinding, // app-owned authoritative, read-only resolver
|
|
68
|
+
* });
|
|
69
|
+
* ```
|
|
70
|
+
*/
|
|
71
|
+
export async function verifyOrderCheckoutAlgorithm(
|
|
72
|
+
input: unknown,
|
|
73
|
+
dependencies: VerifyOrderCheckoutDependencies
|
|
74
|
+
): Promise<VerifyOrderCheckoutResult> {
|
|
75
|
+
let stage: 'validation' | 'auth' | 'config' | 'binding' | 'provider' | 'response' = 'validation';
|
|
76
|
+
let category: 'invalid' | 'rejected' | 'unavailable' = 'invalid';
|
|
77
|
+
try {
|
|
78
|
+
const validation = validateVerifyOrderCheckoutRequest(input);
|
|
79
|
+
if (!validation.success) throw new Error();
|
|
80
|
+
const request = validation.output;
|
|
81
|
+
const { userId, billingConfig } = dependencies;
|
|
82
|
+
stage = 'auth';
|
|
83
|
+
category = 'rejected';
|
|
84
|
+
if (typeof userId !== 'string' || !userId.trim()) throw new Error();
|
|
85
|
+
|
|
86
|
+
stage = 'config';
|
|
87
|
+
category = 'invalid';
|
|
88
|
+
if (
|
|
89
|
+
!Object.hasOwn(billingConfig, request.billingConfigKey) ||
|
|
90
|
+
billingConfig[request.billingConfigKey]?.type !== 'StripeOrder'
|
|
91
|
+
) throw new Error();
|
|
92
|
+
|
|
93
|
+
stage = 'binding';
|
|
94
|
+
category = 'unavailable';
|
|
95
|
+
const binding = await dependencies.resolveOrderBinding({ ...request, userId });
|
|
96
|
+
category = 'rejected';
|
|
97
|
+
if (
|
|
98
|
+
!binding ||
|
|
99
|
+
binding.userId !== userId ||
|
|
100
|
+
binding.sessionId !== request.sessionId ||
|
|
101
|
+
binding.billingConfigKey !== request.billingConfigKey ||
|
|
102
|
+
typeof binding.orderId !== 'string' || !binding.orderId.trim()
|
|
103
|
+
) throw new Error();
|
|
104
|
+
|
|
105
|
+
stage = 'provider';
|
|
106
|
+
category = 'unavailable';
|
|
107
|
+
const session = await dependencies.retrieveStripeSession(request.sessionId);
|
|
108
|
+
stage = 'response';
|
|
109
|
+
category = 'rejected';
|
|
110
|
+
if (
|
|
111
|
+
session.id !== request.sessionId ||
|
|
112
|
+
session.mode !== 'payment' ||
|
|
113
|
+
session.metadata?.userId !== userId ||
|
|
114
|
+
session.metadata?.billingConfigKey !== request.billingConfigKey ||
|
|
115
|
+
session.metadata?.[ORDER_ID_METADATA_KEY] !== binding.orderId
|
|
116
|
+
) throw new Error();
|
|
117
|
+
|
|
118
|
+
// Do not map the webhook snapshot: it includes buyer details and arbitrary
|
|
119
|
+
// metadata and has no session status. Only these allowlisted fields leave here.
|
|
120
|
+
category = 'invalid';
|
|
121
|
+
const result = validateVerifyOrderCheckoutResult({
|
|
122
|
+
sessionId: session.id,
|
|
123
|
+
orderId: binding.orderId,
|
|
124
|
+
billingConfigKey: request.billingConfigKey,
|
|
125
|
+
sessionStatus: session.status,
|
|
126
|
+
paymentStatus: session.payment_status,
|
|
127
|
+
});
|
|
128
|
+
if (!result.success) throw new Error();
|
|
129
|
+
return result.output;
|
|
130
|
+
} catch {
|
|
131
|
+
try {
|
|
132
|
+
// Only code-owned labels: never log the caught error, IDs or metadata.
|
|
133
|
+
// Await also contains a rejected promise if the logging backend changes.
|
|
134
|
+
await logger.warn('[Checkout verification] Failed', { stage, category });
|
|
135
|
+
} catch {
|
|
136
|
+
// Diagnostics must never change the fail-closed public contract.
|
|
137
|
+
}
|
|
138
|
+
// Same message/status through existing handler error mapping; no IDs, cause,
|
|
139
|
+
// provider details or distinctions between missing and foreign bindings.
|
|
140
|
+
throw new Error('Checkout verification denied');
|
|
141
|
+
}
|
|
142
|
+
}
|
|
@@ -28,7 +28,11 @@ import {
|
|
|
28
28
|
detectBulkCollisions,
|
|
29
29
|
DoNotDevError,
|
|
30
30
|
hasRoleAccess,
|
|
31
|
-
|
|
31
|
+
createStatus,
|
|
32
|
+
prepareCreate,
|
|
33
|
+
prepareUpdate,
|
|
34
|
+
statusCan,
|
|
35
|
+
updateCheck,
|
|
32
36
|
} from '@donotdev/core/server';
|
|
33
37
|
import type {
|
|
34
38
|
BulkRequest,
|
|
@@ -37,6 +41,8 @@ import type {
|
|
|
37
41
|
UserRole,
|
|
38
42
|
} from '@donotdev/core/server';
|
|
39
43
|
|
|
44
|
+
import { writtenOf } from './written.js';
|
|
45
|
+
|
|
40
46
|
// =============================================================================
|
|
41
47
|
// Public types
|
|
42
48
|
// =============================================================================
|
|
@@ -52,11 +58,13 @@ export type BulkRowSchema = v.BaseSchema<unknown, any, v.BaseIssue<unknown>>;
|
|
|
52
58
|
/**
|
|
53
59
|
* A prepared insert row passed to the caller-supplied `transact` callback.
|
|
54
60
|
* When {@link ExecuteBulkParams.mintInsertId} is provided, `id` is the minted
|
|
55
|
-
* value
|
|
56
|
-
* the
|
|
61
|
+
* value (a client id never addresses a stored document). Otherwise it is the
|
|
62
|
+
* id the client supplied (a pre-minted id other rows reference, BULK_ACROSS.md
|
|
63
|
+
* "Pre-Minted IDs"), also kept on `row.id`, or the empty string when the
|
|
64
|
+
* storage layer mints its own.
|
|
57
65
|
*/
|
|
58
66
|
export interface PreparedInsert {
|
|
59
|
-
/** Minted
|
|
67
|
+
/** Minted id, else the client-supplied id, else the empty string (the target mints its own). */
|
|
60
68
|
id: string;
|
|
61
69
|
/** Fully stamped row ready for storage. */
|
|
62
70
|
row: Record<string, unknown>;
|
|
@@ -94,10 +102,28 @@ export interface ExecuteBulkParams<TRow = unknown> {
|
|
|
94
102
|
ops: BulkRequest;
|
|
95
103
|
/** Valibot schema validating each insert row. */
|
|
96
104
|
createSchema: BulkRowSchema;
|
|
97
|
-
/**
|
|
105
|
+
/**
|
|
106
|
+
* `createSchemas(entity).draft`: drafts saved incomplete (CRUD rule 5). Required as soon
|
|
107
|
+
* as a draft row is sent: a draft without it is rejected (`invalid-argument`), never
|
|
108
|
+
* validated as a create.
|
|
109
|
+
*/
|
|
98
110
|
draftCreateSchema?: BulkRowSchema;
|
|
99
|
-
/**
|
|
111
|
+
/** `createSchemas(entity).update`: update patches (CRUD rules 2, 5). */
|
|
100
112
|
updateSchema: BulkRowSchema;
|
|
113
|
+
/**
|
|
114
|
+
* Reads the stored rows of the updated ids (application field names, keyed by id).
|
|
115
|
+
* Called once, before validation, when the bulk carries updates: the stored row
|
|
116
|
+
* gives each patch its status and a published draft its whole record
|
|
117
|
+
* (`prepareUpdate`, as on the client). An updated id missing
|
|
118
|
+
* from the result is rejected (`not-found`). Required as soon as the bulk carries
|
|
119
|
+
* updates: an update without it is rejected (`internal`, a configuration error),
|
|
120
|
+
* never validated by its patch status alone. Every target passes it: Firestore,
|
|
121
|
+
* Supabase and Vercel read their store; the GraphQL / REST-CRUD server aids
|
|
122
|
+
* forward the consumer's `readStored` option.
|
|
123
|
+
*/
|
|
124
|
+
readStored?: (
|
|
125
|
+
ids: readonly string[]
|
|
126
|
+
) => Promise<ReadonlyMap<string, Record<string, unknown>>>;
|
|
101
127
|
/** Per-bucket required roles. Missing entries are treated as "no bucket allowed". */
|
|
102
128
|
access: EntityAccessConfig;
|
|
103
129
|
/** Authenticated caller id (for metadata + audit). */
|
|
@@ -185,12 +211,17 @@ const EMPTY_BULK_RESPONSE: BulkResponse = Object.freeze({
|
|
|
185
211
|
* 4. Per-bucket ACL — for each populated bucket, asserts the caller's role
|
|
186
212
|
* clears the corresponding `access.{create|update|delete}`. A missing
|
|
187
213
|
* role on a populated bucket is a configuration error and is rejected.
|
|
188
|
-
* 5. Per-row validation —
|
|
189
|
-
*
|
|
190
|
-
*
|
|
214
|
+
* 5. Per-row validation — the CRUD rules (`prepareCreate` / `prepareUpdate`,
|
|
215
|
+
* core/schemas crud/), the stored rows read once with `readStored` (updates
|
|
216
|
+
* without it → `internal`; an updated id with no stored row → `not-found`).
|
|
217
|
+
* The first failure throws `validation-failed` (wire: `invalid-argument`)
|
|
218
|
+
* naming `inserts[i]` / `updates[i]`. Unknown fields are logged, not written.
|
|
219
|
+
* What is stored is the rules' `written`, never the raw row.
|
|
191
220
|
* 6. Id minting — if `mintInsertId` is supplied, every insert gets a fresh
|
|
192
|
-
* id stamped onto its {@link PreparedInsert}. Otherwise
|
|
193
|
-
* the
|
|
221
|
+
* id stamped onto its {@link PreparedInsert}. Otherwise a client-supplied
|
|
222
|
+
* `id` is kept (on the row and as `PreparedInsert.id`; the create schema
|
|
223
|
+
* excludes it, it is restored after validation), else `id` is `""` and the
|
|
224
|
+
* storage layer mints its own.
|
|
194
225
|
* 7. Metadata stamping — `stampInsertMetadata` / `stampUpdateMetadata` run
|
|
195
226
|
* per row / per patch if provided.
|
|
196
227
|
* 8. `transact(prepared)` runs exactly once. Must be atomic. Throws
|
|
@@ -212,8 +243,12 @@ const EMPTY_BULK_RESPONSE: BulkResponse = Object.freeze({
|
|
|
212
243
|
* @throws {DoNotDevError} `invalid-argument` on wire-schema failure, per-row
|
|
213
244
|
* validation failure, or collision (wrapped for callers that only rethrow
|
|
214
245
|
* `DoNotDevError`).
|
|
246
|
+
* @throws {DoNotDevError} `not-found` when an updated id has no stored row
|
|
247
|
+
* (`readStored`).
|
|
215
248
|
* @throws {DoNotDevError} `permission-denied` when the caller's role cannot
|
|
216
249
|
* satisfy a populated bucket's access requirement.
|
|
250
|
+
* @throws {DoNotDevError} `internal` when the bulk carries updates but no
|
|
251
|
+
* `readStored` is configured.
|
|
217
252
|
* @throws {DoNotDevError} `internal` when the `transact` return value fails
|
|
218
253
|
* {@link BulkResponseSchema}.
|
|
219
254
|
*
|
|
@@ -230,6 +265,7 @@ const EMPTY_BULK_RESPONSE: BulkResponse = Object.freeze({
|
|
|
230
265
|
* access,
|
|
231
266
|
* uid,
|
|
232
267
|
* userRole,
|
|
268
|
+
* readStored: async (ids) => new Map((await db.getRows(ids)).map((row) => [row.id, row])),
|
|
233
269
|
* mintInsertId: () => crypto.randomUUID(),
|
|
234
270
|
* stampInsertMetadata: (row, uid) => ({
|
|
235
271
|
* ...row,
|
|
@@ -269,6 +305,7 @@ export async function executeBulk<TRow = unknown>(
|
|
|
269
305
|
uid,
|
|
270
306
|
userRole,
|
|
271
307
|
transact,
|
|
308
|
+
readStored,
|
|
272
309
|
mintInsertId,
|
|
273
310
|
stampInsertMetadata,
|
|
274
311
|
stampUpdateMetadata,
|
|
@@ -359,52 +396,82 @@ export async function executeBulk<TRow = unknown>(
|
|
|
359
396
|
}
|
|
360
397
|
}
|
|
361
398
|
|
|
362
|
-
// 5. Per-row validation
|
|
363
|
-
//
|
|
399
|
+
// 5. Per-row validation: the CRUD rules (core/schemas crud/: `prepareCreate`,
|
|
400
|
+
// `prepareUpdate`), as on the client. First failure wins, named by its bucket
|
|
401
|
+
// index. What is stored is the rules' `written`, never the raw row.
|
|
402
|
+
const noDraftSchema = (locator: string): never => {
|
|
403
|
+
throw new DoNotDevError(
|
|
404
|
+
`Validation failed on ${locator}: draft row sent to ${collection} but no draft schema is configured`,
|
|
405
|
+
'invalid-argument'
|
|
406
|
+
);
|
|
407
|
+
};
|
|
408
|
+
// Without a draft schema, no draft row passes the guards below: `create` only fills the slot.
|
|
409
|
+
const schemas = {
|
|
410
|
+
create: createSchema,
|
|
411
|
+
draft: draftCreateSchema ?? createSchema,
|
|
412
|
+
update: updateSchema,
|
|
413
|
+
};
|
|
414
|
+
const insertRows: { row: Record<string, unknown>; id: string | null }[] = [];
|
|
364
415
|
for (let i = 0; i < inserts.length; i++) {
|
|
365
|
-
const
|
|
366
|
-
|
|
367
|
-
const
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
isDraft && draftCreateSchema ? draftCreateSchema : createSchema;
|
|
372
|
-
// Only inject default `status` when validating against the draft schema.
|
|
373
|
-
// This avoids breaking createSchema-only tests/entities that don't define
|
|
374
|
-
// `status` in their schema shape (valibot's `v.object` is strict by
|
|
375
|
-
// default).
|
|
376
|
-
const payloadForValidation =
|
|
377
|
-
isDraft && draftCreateSchema ? { ...rowObj, status } : rowObj;
|
|
378
|
-
validateRow(payloadForValidation, schemaToUse, `inserts[${i}]`);
|
|
416
|
+
const rowObj = inserts[i]! as unknown as Record<string, unknown>;
|
|
417
|
+
if (!draftCreateSchema && statusCan(createStatus(rowObj), 'saveIncomplete')) noDraftSchema(`inserts[${i}]`);
|
|
418
|
+
const row = writtenOf(prepareCreate(schemas, rowObj), collection, `inserts[${i}]`);
|
|
419
|
+
// A client id is a pre-minted id other rows reference: the rules never write
|
|
420
|
+
// `id`, so it travels beside the row.
|
|
421
|
+
insertRows.push({ row, id: typeof rowObj.id === 'string' ? rowObj.id : null });
|
|
379
422
|
}
|
|
423
|
+
// The stored rows give each patch its status and the publish check its record.
|
|
424
|
+
if (updates.length > 0 && !readStored) {
|
|
425
|
+
throw new DoNotDevError(
|
|
426
|
+
`Bulk update requested on ${collection} but no readStored is configured: the stored row decides each patch's rules`,
|
|
427
|
+
'internal'
|
|
428
|
+
);
|
|
429
|
+
}
|
|
430
|
+
const stored =
|
|
431
|
+
updates.length > 0 && readStored
|
|
432
|
+
? await readStored(updates.map((u) => u.id))
|
|
433
|
+
: new Map<string, Record<string, unknown>>();
|
|
434
|
+
const updatePatches: Record<string, unknown>[] = [];
|
|
380
435
|
for (let i = 0; i < updates.length; i++) {
|
|
381
|
-
|
|
436
|
+
const { id, patch } = updates[i]!;
|
|
437
|
+
const locator = `updates[${i}]`;
|
|
438
|
+
const storedRow = stored.get(id);
|
|
439
|
+
if (!storedRow) {
|
|
440
|
+
throw new DoNotDevError(
|
|
441
|
+
`Document not found on ${locator}: ${collection}/${id}`,
|
|
442
|
+
'not-found'
|
|
443
|
+
);
|
|
444
|
+
}
|
|
445
|
+
if (!draftCreateSchema && updateCheck(patch as Record<string, unknown>, storedRow).schemaKey === 'draft') {
|
|
446
|
+
noDraftSchema(locator);
|
|
447
|
+
}
|
|
448
|
+
updatePatches.push(
|
|
449
|
+
writtenOf(
|
|
450
|
+
prepareUpdate(schemas, { id, patch: patch as Record<string, unknown>, stored: storedRow }),
|
|
451
|
+
collection,
|
|
452
|
+
locator
|
|
453
|
+
)
|
|
454
|
+
);
|
|
382
455
|
}
|
|
383
456
|
|
|
384
457
|
// 6. Id minting (if provided). Minting at this layer means `transact`
|
|
385
458
|
// receives stable ids — crucial for Firestore's retry-able transaction
|
|
386
459
|
// callbacks where the callback body may run more than once.
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
const status =
|
|
394
|
-
(rowRecord.status as string | undefined) ?? DEFAULT_STATUS_VALUE;
|
|
395
|
-
const id = mintInsertId ? mintInsertId() : '';
|
|
396
|
-
const stamped = stampInsertMetadata
|
|
397
|
-
? stampInsertMetadata({ ...rowRecord, status }, uid)
|
|
398
|
-
: ({ ...rowRecord, status } as Record<string, unknown>);
|
|
460
|
+
// Without minting, a client id is kept (row + PreparedInsert.id) for the
|
|
461
|
+
// target to store; with minting, the minted id wins.
|
|
462
|
+
const preparedInserts: PreparedInsert[] = insertRows.map(({ row, id: clientId }) => {
|
|
463
|
+
const id = mintInsertId ? mintInsertId() : (clientId ?? '');
|
|
464
|
+
const withId = !mintInsertId && clientId !== null ? { ...row, id: clientId } : row;
|
|
465
|
+
const stamped = stampInsertMetadata ? stampInsertMetadata(withId, uid) : withId;
|
|
399
466
|
return { id, row: stamped };
|
|
400
467
|
});
|
|
401
468
|
|
|
402
469
|
// 7. Update metadata stamping.
|
|
403
|
-
const preparedUpdates: PreparedUpdate[] = updates.map((u) => ({
|
|
470
|
+
const preparedUpdates: PreparedUpdate[] = updates.map((u, i) => ({
|
|
404
471
|
id: u.id,
|
|
405
472
|
patch: stampUpdateMetadata
|
|
406
|
-
? stampUpdateMetadata(
|
|
407
|
-
:
|
|
473
|
+
? stampUpdateMetadata(updatePatches[i]!, uid)
|
|
474
|
+
: updatePatches[i]!,
|
|
408
475
|
}));
|
|
409
476
|
|
|
410
477
|
// 8. Atomic dispatch. Propagates any `transact` error verbatim — the
|
|
@@ -444,41 +511,3 @@ export async function executeBulk<TRow = unknown>(
|
|
|
444
511
|
// =============================================================================
|
|
445
512
|
// Internal helpers
|
|
446
513
|
// =============================================================================
|
|
447
|
-
|
|
448
|
-
/**
|
|
449
|
-
* Validate a row against a Valibot schema and rethrow a `DoNotDevError`
|
|
450
|
-
* prefixed with the bucket position so callers can point at the offending
|
|
451
|
-
* row. Keeps the hot path free of try/catch overhead when no schema is
|
|
452
|
-
* supplied.
|
|
453
|
-
*
|
|
454
|
-
* @param value - Row or patch to validate.
|
|
455
|
-
* @param schema - Valibot schema.
|
|
456
|
-
* @param locator - Human-readable pointer such as `inserts[2]`.
|
|
457
|
-
*
|
|
458
|
-
* @example
|
|
459
|
-
* ```typescript
|
|
460
|
-
* validateRow(inserts[i], createSchema, `inserts[${i}]`);
|
|
461
|
-
* ```
|
|
462
|
-
*
|
|
463
|
-
* @internal
|
|
464
|
-
*/
|
|
465
|
-
function validateRow(
|
|
466
|
-
value: unknown,
|
|
467
|
-
schema: BulkRowSchema,
|
|
468
|
-
locator: string
|
|
469
|
-
): void {
|
|
470
|
-
const parsed = v.safeParse(schema, value);
|
|
471
|
-
if (parsed.success) return;
|
|
472
|
-
|
|
473
|
-
const messages = parsed.issues
|
|
474
|
-
.map(
|
|
475
|
-
(issue) =>
|
|
476
|
-
`${issue.path?.map((p) => p.key).join('.') || 'root'}: ${issue.message}`
|
|
477
|
-
)
|
|
478
|
-
.join('; ');
|
|
479
|
-
throw new DoNotDevError(
|
|
480
|
-
`Validation failed on ${locator}: ${messages}`,
|
|
481
|
-
'invalid-argument',
|
|
482
|
-
{ details: { validationErrors: parsed.issues } }
|
|
483
|
-
);
|
|
484
|
-
}
|
package/src/shared/crud/index.ts
CHANGED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// packages/functions/src/shared/crud/written.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview What a server write stores
|
|
5
|
+
* @description The server side of a CRUD rule result (`prepareCreate` / `prepareUpdate` /
|
|
6
|
+
* `prepareRemove`, core/schemas crud/): logs the unknown fields (CRUD rule 8: neither
|
|
7
|
+
* silent nor blocking) and returns the stored values or throws. Every server write site
|
|
8
|
+
* (bulk, create, update, entity store) calls it.
|
|
9
|
+
*
|
|
10
|
+
* @version 0.1.0
|
|
11
|
+
* @since 0.3.0
|
|
12
|
+
* @author AMBROISE PARK Consulting
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { DoNotDevError } from '@donotdev/core/server';
|
|
16
|
+
import type { PreparedWrite } from '@donotdev/core/server';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The values a server write stores.
|
|
20
|
+
*
|
|
21
|
+
* @param result - The CRUD rule result
|
|
22
|
+
* @param collection - Collection written (named in the log and the error)
|
|
23
|
+
* @param locator - Write site / row (e.g. `update`, `inserts[2]`)
|
|
24
|
+
* @returns The rule's `written`
|
|
25
|
+
* @throws {DoNotDevError} `invalid-argument` with `details.validationErrors` (the server wire
|
|
26
|
+
* contract, a Firebase `FunctionsErrorCode`) when the write is invalid
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```typescript
|
|
30
|
+
* const row = writtenOf(prepareCreate(schemas, payload), collection, 'create');
|
|
31
|
+
* ```
|
|
32
|
+
*
|
|
33
|
+
* @version 0.1.0
|
|
34
|
+
* @since 0.3.0
|
|
35
|
+
* @author AMBROISE PARK Consulting
|
|
36
|
+
*/
|
|
37
|
+
export function writtenOf(
|
|
38
|
+
result: PreparedWrite,
|
|
39
|
+
collection: string,
|
|
40
|
+
locator: string
|
|
41
|
+
): Record<string, unknown> {
|
|
42
|
+
if (result.unknownKeys.length > 0) {
|
|
43
|
+
console.warn(
|
|
44
|
+
`[dndev] ${collection} ${locator}: fields the entity does not have, not written: ${result.unknownKeys.join(', ')}`
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
if (result.ok) return result.written;
|
|
48
|
+
const messages = result.issues
|
|
49
|
+
.map((issue) => `${issue.path?.map((p) => String(p.key)).join('.') || 'root'}: ${issue.message}`)
|
|
50
|
+
.join('; ');
|
|
51
|
+
throw new DoNotDevError(
|
|
52
|
+
`Validation failed on ${collection} ${locator}: ${messages}`,
|
|
53
|
+
'invalid-argument',
|
|
54
|
+
{ details: { validationErrors: result.issues } }
|
|
55
|
+
);
|
|
56
|
+
}
|
package/src/shared/index.d.ts
CHANGED
|
@@ -36,15 +36,6 @@ export * from './github.js';
|
|
|
36
36
|
*/
|
|
37
37
|
export * from './metadata.js';
|
|
38
38
|
|
|
39
|
-
/**
|
|
40
|
-
* Schema validation utilities
|
|
41
|
-
*
|
|
42
|
-
* @version 0.1.0
|
|
43
|
-
* @since 0.0.1
|
|
44
|
-
* @author AMBROISE PARK Consulting
|
|
45
|
-
*/
|
|
46
|
-
export * from './schema.js';
|
|
47
|
-
|
|
48
39
|
/**
|
|
49
40
|
* General utility functions
|
|
50
41
|
*
|
package/src/shared/index.ts
CHANGED
package/src/shared/utils.ts
CHANGED
|
@@ -9,7 +9,6 @@
|
|
|
9
9
|
* @author AMBROISE PARK Consulting
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
-
import * as v from 'valibot';
|
|
13
12
|
|
|
14
13
|
import { DoNotDevError } from '@donotdev/core/server';
|
|
15
14
|
import type { OAuthPartnerId, UserRole } from '@donotdev/core/server';
|
|
@@ -109,48 +108,6 @@ export function createErrorResponse(error: unknown): {
|
|
|
109
108
|
};
|
|
110
109
|
}
|
|
111
110
|
|
|
112
|
-
/**
|
|
113
|
-
* Validates document data
|
|
114
|
-
*
|
|
115
|
-
* @version 0.1.0
|
|
116
|
-
* @since 0.0.1
|
|
117
|
-
* @author AMBROISE PARK Consulting
|
|
118
|
-
*/
|
|
119
|
-
export function validateDocument(
|
|
120
|
-
data: unknown,
|
|
121
|
-
schema?: v.GenericSchema
|
|
122
|
-
): void {
|
|
123
|
-
if (!data || typeof data !== 'object') {
|
|
124
|
-
throw new Error('Invalid document data');
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
if (Array.isArray(data)) {
|
|
128
|
-
throw new Error('Document data cannot be an array');
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
// Run Valibot schema validation when a schema is provided
|
|
132
|
-
if (schema) {
|
|
133
|
-
try {
|
|
134
|
-
v.parse(schema, data);
|
|
135
|
-
} catch (error) {
|
|
136
|
-
if (v.isValiError(error)) {
|
|
137
|
-
const messages = error.issues
|
|
138
|
-
.map(
|
|
139
|
-
(issue) =>
|
|
140
|
-
`${issue.path?.map((p) => p.key).join('.') || 'root'}: ${issue.message}`
|
|
141
|
-
)
|
|
142
|
-
.join('; ');
|
|
143
|
-
throw new DoNotDevError(
|
|
144
|
-
`Validation failed: ${messages}`,
|
|
145
|
-
'invalid-argument',
|
|
146
|
-
{ details: { validationErrors: error.issues } }
|
|
147
|
-
);
|
|
148
|
-
}
|
|
149
|
-
throw error;
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
|
|
154
111
|
/**
|
|
155
112
|
* Validates a Firestore collection name from client-supplied schema.
|
|
156
113
|
*
|