@pgxsinkit/server 0.2.4 → 0.2.6

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.
@@ -8,6 +8,7 @@ import type {
8
8
  AuthoritativeWriteRequest,
9
9
  BatchMutationRequest,
10
10
  JwtClaims,
11
+ ManagedFieldApplyOn,
11
12
  MutationAck,
12
13
  RegistryRelations,
13
14
  SyncTableEntry,
@@ -18,6 +19,7 @@ import {
18
19
  batchMutationRequestSchema,
19
20
  getOmittedProjectedColumns as getOmittedProjectionColumns,
20
21
  getProjectedColumns,
22
+ isManagedFieldGuarded,
21
23
  resolveServerVersionColumnName,
22
24
  } from "@pgxsinkit/contracts";
23
25
 
@@ -28,6 +30,8 @@ import { readSqlState } from "../sql-state";
28
30
  import {
29
31
  executePlpgsqlBatch,
30
32
  expectedApplyFingerprint,
33
+ resolveApplyFunctionSchema,
34
+ type ApplyFunctionRenderOptions,
31
35
  type MutationConflict,
32
36
  verifyRlsAuthHelpers,
33
37
  } from "./plpgsql-apply";
@@ -44,7 +48,9 @@ import type { TransactionClient } from "./types";
44
48
  export type StartupVerificationMode = "in-process" | "deploy-time";
45
49
 
46
50
  const { createInsertSchema: createMutationInsertSchema } = createSchemaFactory({
47
- coerce: { date: true },
51
+ // Mutation payloads cross a JSON boundary, so bigint-mode Drizzle columns arrive as decimal strings.
52
+ // Coerce only while validating; the original JSON payload remains string-valued for the SQL apply path.
53
+ coerce: { date: true, bigint: true },
48
54
  });
49
55
 
50
56
  type RouteReadQueryClient = Pick<PgAsyncDatabase<PgQueryResultHKT, AnyRelations>, "select">;
@@ -61,13 +67,30 @@ export function createMutationHandler<TRegistry extends SyncTableRegistry>(
61
67
  resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null,
62
68
  startupVerification: StartupVerificationMode = "in-process",
63
69
  logTimings = false,
70
+ // ADR-0054: the roles the installed artifact was generated with. The ACL is INSIDE the fingerprinted
71
+ // body, so the expected fingerprint below is only reproducible when this matches the generate flags.
72
+ applyFunctionGrantExecuteTo: readonly string[] = [],
73
+ // The schema the installed artifact was generated into (`pgxsinkit-generate --function-schema`).
74
+ // It is BOTH a fingerprint input (the body embeds the qualified name) and the name this server must
75
+ // CALL, so one value drives both — a server that knows the fingerprint but calls the function
76
+ // unqualified would resolve through `search_path` and, in the usual case, find nothing.
77
+ applyFunctionSchema?: string,
64
78
  ): { batch: FetchHandler; authoritative: FetchHandler } {
65
79
  let startupReadyPromise: Promise<void> | undefined;
66
80
 
81
+ const applyFunctionRenderOptions: ApplyFunctionRenderOptions = {
82
+ ...(applyFunctionGrantExecuteTo.length > 0 ? { grantExecuteTo: applyFunctionGrantExecuteTo } : {}),
83
+ ...(applyFunctionSchema ? { functionSchema: applyFunctionSchema } : {}),
84
+ };
85
+ // Validated once here (the same rule the renderer applies) rather than per request, so a bad schema
86
+ // name fails at server construction instead of on the first write.
87
+ const resolvedApplyFunctionSchema = resolveApplyFunctionSchema(applyFunctionRenderOptions.functionSchema);
88
+ const applyInvocationOptions = resolvedApplyFunctionSchema ? { functionSchema: resolvedApplyFunctionSchema } : {};
89
+
67
90
  // ADR-0030: the fingerprint this server expects for its registry + applier codegen, computed ONCE per
68
91
  // server instance. Every `executePlpgsqlBatch` passes it so the installed apply function can verify
69
92
  // itself in-body (SQLSTATE 'PXS01' on drift) — this replaces the deleted startup verify.
70
- const expectedFingerprint = expectedApplyFingerprint(registry);
93
+ const expectedFingerprint = expectedApplyFingerprint(registry, applyFunctionRenderOptions);
71
94
 
72
95
  // Per-request timing scratch (opt-in). authMs/applyMs are filled at the narrow phase call sites inside
73
96
  // the handler; totalMs + status are measured by `withTiming` wrapping the returned handler. A fresh
@@ -190,9 +213,7 @@ export function createMutationHandler<TRegistry extends SyncTableRegistry>(
190
213
  if (payloadKeys.length === 0) {
191
214
  throw new Error("At least one field must be provided");
192
215
  }
193
- createMutationInsertSchema(syncEntry.table as AnyPgTable)
194
- .partial()
195
- .parse(normalizedPayload);
216
+ buildUpdateValidationSchema(syncEntry).parse(normalizedPayload);
196
217
  } else if (mutation.kind === "create") {
197
218
  buildCreateValidationSchema(syncEntry).parse(normalizedPayload);
198
219
  }
@@ -352,6 +373,7 @@ export function createMutationHandler<TRegistry extends SyncTableRegistry>(
352
373
  shouldApplyRlsContext,
353
374
  userClaims,
354
375
  expectedFingerprint,
376
+ applyInvocationOptions,
355
377
  );
356
378
  if (timing) timing.applyMs = perfNow() - applyStart;
357
379
 
@@ -575,6 +597,7 @@ export function createMutationHandler<TRegistry extends SyncTableRegistry>(
575
597
  shouldApplyRlsContext,
576
598
  userClaims,
577
599
  expectedFingerprint,
600
+ applyInvocationOptions,
578
601
  );
579
602
  if (timing) timing.applyMs = perfNow() - applyStart;
580
603
 
@@ -877,7 +900,12 @@ function getUuidClaim(claims: JwtClaims, key: string): string | null {
877
900
  return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value) ? value : null;
878
901
  }
879
902
 
880
- function findManagedFieldViolations(
903
+ /**
904
+ * The server-managed payload keys a mutation must not carry — the 400 guard (see
905
+ * {@link getGuardedManagedFields} for what counts as managed per operation, notably that a create-only
906
+ * managed field is guarded on update too). Exported for direct unit coverage.
907
+ */
908
+ export function findManagedFieldViolations(
881
909
  entry: SyncTableEntry,
882
910
  mutationKind: BatchMutationRequest["mutations"][number]["kind"],
883
911
  payload: unknown,
@@ -886,7 +914,7 @@ function findManagedFieldViolations(
886
914
  return [];
887
915
  }
888
916
 
889
- const managedFields = getManagedFieldsForOperation(entry, mutationKind);
917
+ const managedFields = getGuardedManagedFields(entry, mutationKind);
890
918
  if (managedFields.length === 0) {
891
919
  return [];
892
920
  }
@@ -1012,7 +1040,16 @@ function findProjectedFieldViolations(
1012
1040
  ];
1013
1041
  }
1014
1042
 
1015
- function sanitizeRestrictedFields(batch: BatchMutationRequest, registry: SyncTableRegistry): BatchMutationRequest {
1043
+ /**
1044
+ * Defense in depth behind the 400 guard: strip every server-owned key from each payload before apply, so
1045
+ * a caller that reaches this code path without the request-level check (or a key spelled as the DB column
1046
+ * name rather than the property key) still cannot set a managed or projected-away column. Exported for
1047
+ * direct unit coverage.
1048
+ */
1049
+ export function sanitizeRestrictedFields(
1050
+ batch: BatchMutationRequest,
1051
+ registry: SyncTableRegistry,
1052
+ ): BatchMutationRequest {
1016
1053
  return {
1017
1054
  mutations: batch.mutations.map((mutation) => {
1018
1055
  if (mutation.kind === "delete") {
@@ -1025,7 +1062,7 @@ function sanitizeRestrictedFields(batch: BatchMutationRequest, registry: SyncTab
1025
1062
  return mutation;
1026
1063
  }
1027
1064
 
1028
- const managedFields = getManagedFieldsForOperation(entry as SyncTableEntry, mutation.kind);
1065
+ const managedFields = getGuardedManagedFields(entry as SyncTableEntry, mutation.kind);
1029
1066
  const projectedFields = getProjectedAwayFields(entry as SyncTableEntry);
1030
1067
 
1031
1068
  if (managedFields.length === 0 && projectedFields.length === 0) {
@@ -1062,7 +1099,7 @@ function sanitizeRestrictedFields(batch: BatchMutationRequest, registry: SyncTab
1062
1099
  */
1063
1100
  export function buildCreateValidationSchema(entry: SyncTableEntry) {
1064
1101
  const createSchema = createMutationInsertSchema(entry.table as AnyPgTable);
1065
- const managedCreateKeys = getManagedFieldsForOperation(entry, "create").map((field) => field.propertyKey);
1102
+ const managedCreateKeys = getGuardedManagedFields(entry, "create").map((field) => field.propertyKey);
1066
1103
  if (managedCreateKeys.length === 0) {
1067
1104
  return createSchema;
1068
1105
  }
@@ -1074,19 +1111,36 @@ export function buildCreateValidationSchema(entry: SyncTableEntry) {
1074
1111
  return createSchema.omit(omitMask);
1075
1112
  }
1076
1113
 
1077
- function getManagedFieldsForOperation(
1078
- entry: SyncTableEntry,
1079
- mutationKind: BatchMutationRequest["mutations"][number]["kind"],
1080
- ) {
1081
- if (mutationKind === "delete") {
1082
- return [];
1114
+ /**
1115
+ * The zod schema used to validate an `update` payload: the insert schema made `partial()` (an update is a
1116
+ * patch — only the sent keys are validated), minus every server-managed key. This is the update-side
1117
+ * counterpart of {@link buildCreateValidationSchema}: a field managed on update is stamped by the server,
1118
+ * and a **create-only** managed field is inert on update (the generated apply function omits it from the
1119
+ * UPDATE SET candidates), so neither is a settable key of an update payload. Both are already
1120
+ * 400-rejected by {@link findManagedFieldViolations}; omitting them keeps the schema an accurate
1121
+ * statement of what an update may carry.
1122
+ */
1123
+ export function buildUpdateValidationSchema(entry: SyncTableEntry) {
1124
+ const updateSchema = createMutationInsertSchema(entry.table as AnyPgTable).partial();
1125
+ const managedKeys = getGuardedManagedFields(entry, "update").map((field) => field.propertyKey);
1126
+ if (managedKeys.length === 0) {
1127
+ return updateSchema;
1083
1128
  }
1129
+ const omitMask = Object.fromEntries(managedKeys.map((key) => [key, true as const])) as Parameters<
1130
+ typeof updateSchema.omit
1131
+ >[0];
1132
+ return updateSchema.omit(omitMask);
1133
+ }
1084
1134
 
1135
+ function getManagedFields(
1136
+ entry: SyncTableEntry,
1137
+ matches: (field: { applyOn: readonly ManagedFieldApplyOn[] }) => boolean,
1138
+ ) {
1085
1139
  const columns = getColumns(entry.table as AnyPgTable);
1086
1140
  const columnMap = new Map(Object.entries(columns).map(([propertyKey, column]) => [propertyKey, column.name]));
1087
1141
 
1088
1142
  return (entry.governance?.managedFields ?? [])
1089
- .filter((field) => field.applyOn.includes(mutationKind))
1143
+ .filter((field) => matches(field))
1090
1144
  .map((field) => ({
1091
1145
  propertyKey: field.column,
1092
1146
  columnName: columnMap.get(field.column) ?? field.column,
@@ -1094,6 +1148,31 @@ function getManagedFieldsForOperation(
1094
1148
  }));
1095
1149
  }
1096
1150
 
1151
+ function getManagedFieldsForOperation(
1152
+ entry: SyncTableEntry,
1153
+ mutationKind: BatchMutationRequest["mutations"][number]["kind"],
1154
+ ) {
1155
+ if (mutationKind === "delete") {
1156
+ return [];
1157
+ }
1158
+
1159
+ return getManagedFields(entry, (field) => field.applyOn.includes(mutationKind));
1160
+ }
1161
+
1162
+ /**
1163
+ * The fields the request-path guards treat as **server-owned** for `mutationKind` — the one set the
1164
+ * violation check flags, the sanitizer strips, and the validation schema omits. This resolves the
1165
+ * governance specs to `{ propertyKey, columnName, strategy }`; WHICH of them are server-owned is not
1166
+ * decided here but by contracts' {@link isManagedFieldGuarded}, the single definition of the guard rule
1167
+ * (shared with the client's `stripManagedFields` and the apply-function generator).
1168
+ */
1169
+ function getGuardedManagedFields(
1170
+ entry: SyncTableEntry,
1171
+ mutationKind: BatchMutationRequest["mutations"][number]["kind"],
1172
+ ) {
1173
+ return getManagedFields(entry, (field) => isManagedFieldGuarded(field, mutationKind));
1174
+ }
1175
+
1097
1176
  function getProjectedAwayFields(entry: SyncTableEntry) {
1098
1177
  return getOmittedProjectionColumns(entry).map(({ propertyKey, columnName }) => ({
1099
1178
  propertyKey,