@sfxcode/mongocamp-server-core 2.6.1 → 2.7.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.
package/dist/index.d.mts CHANGED
@@ -290,8 +290,17 @@ declare class AuthorizedUser {
290
290
  readonly roles: Role[];
291
291
  readonly grants: Grant[];
292
292
  readonly isAdmin: boolean;
293
- constructor(user: UserInformation, roles: Role[]);
293
+ /**
294
+ * The user an administrator acts for (2.7.0, header `X-AUTH-ACT-AS`): the rights of the request stay the administrator's, but the
295
+ * behaviours (owner, timestamps, versioned, audit), the read scopes and the events see this user.
296
+ */
297
+ readonly actingFor?: AuthorizedUser;
298
+ constructor(user: UserInformation, roles: Role[], actingFor?: AuthorizedUser);
294
299
  get userId(): string;
300
+ /** The user the request acts for: the one of `X-AUTH-ACT-AS`, else the logged in user itself. */
301
+ get acting(): AuthorizedUser;
302
+ /** This user acting for another one (2.7.0). */
303
+ actingAs(other: AuthorizedUser): AuthorizedUser;
295
304
  /** Collection grants, and the bucket meta grants as grants for the `.files` collection of the bucket. */
296
305
  get collectionGrants(): Grant[];
297
306
  get bucketGrants(): Grant[];
@@ -416,6 +425,12 @@ interface LoginResult {
416
425
  userProfile: UserProfile;
417
426
  expirationDate: string;
418
427
  }
428
+ /**
429
+ * The header with the id of the user an administrator acts for (2.7.0): a trusted backend (e.g. the server routes of an application with
430
+ * the api key of an administrator) writes and reads documents as its user, so owner, timestamps, versioned and audit see that user. The
431
+ * rights stay the administrator's. Refused (403) for every caller that is no administrator, 401 for a user that does not exist.
432
+ */
433
+ declare const ActAsHeader = "X-AUTH-ACT-AS";
419
434
  declare class AuthService {
420
435
  private readonly config;
421
436
  private readonly version;
@@ -495,6 +510,12 @@ interface TimestampsOptions {
495
510
  createdBy?: FieldOption;
496
511
  /** The user of the last change (`true`: `updatedBy`); not written unless set. */
497
512
  updatedBy?: FieldOption;
513
+ /**
514
+ * An insert by an administrator — also one acting for a user (`X-AUTH-ACT-AS`) — keeps the values it sends for these fields (2.7.0;
515
+ * imports and restores keep their creation time and users); missing ones are written as usual. Other callers cannot send them.
516
+ * Default false.
517
+ */
518
+ preserveOnInsert?: boolean;
498
519
  }
499
520
  /** The documents a user may read when the read rule is a function: a filter combined with every read (it can only narrow). */
500
521
  type ReadScope = (context: {
@@ -508,6 +529,11 @@ interface OwnerOptions {
508
529
  read?: 'own' | 'all' | ReadScope;
509
530
  /** Administrators read and write every document (default true). */
510
531
  adminBypass?: boolean;
532
+ /**
533
+ * An insert by an administrator — also one acting for a user (`X-AUTH-ACT-AS`) — keeps the owner it sends (2.7.0; imports that create
534
+ * documents for their users); without one the user of the request owns the document as usual. Default false.
535
+ */
536
+ preserveOnInsert?: boolean;
511
537
  }
512
538
  interface SoftDeleteOptions {
513
539
  /** Default `deletedAt`. */
@@ -543,11 +569,13 @@ interface ResolvedBehaviours {
543
569
  updatedAt: string;
544
570
  createdBy?: string;
545
571
  updatedBy?: string;
572
+ preserveOnInsert?: boolean;
546
573
  };
547
574
  owner?: {
548
575
  field: string;
549
576
  read: 'own' | 'all' | ReadScope;
550
577
  adminBypass: boolean;
578
+ preserveOnInsert?: boolean;
551
579
  };
552
580
  softDelete?: {
553
581
  field: string;
@@ -1657,8 +1685,10 @@ interface EventBase {
1657
1685
  /** The name of the hook, e.g. `document:create`. */
1658
1686
  name: string;
1659
1687
  }
1688
+ /** `actedBy` (2.7.0): the administrator who sent the request when it acted for `user` (header `X-AUTH-ACT-AS`). */
1660
1689
  type ByUser<T = object> = {
1661
1690
  user: UserInformation;
1691
+ actedBy?: UserInformation;
1662
1692
  } & T;
1663
1693
  type Document$1 = Record<string, unknown>;
1664
1694
  /** The fields of `HttpRequestStartEvent` / `HttpRequestCompletedEvent`. */
@@ -1878,6 +1908,9 @@ declare class ConfigPersistence {
1878
1908
  * 2.6.0: a database created before 2.2.0 stored the old default 401 of `AUTH_GRANT_DENIED_STATUS` at its first start, and kept answering
1879
1909
  * 401 for a missing grant. A stored 401 that no update set (no `changedAt`, written since 2.6.0) becomes the default 403 once; an
1880
1910
  * administrator who wants 401 patches it again (then it is marked and stays).
1911
+ *
1912
+ * 2.7.1: the same for an old default of `CORS_HEADERS_EXPOSED` (see `LegacyCorsHeadersExposed`). Without `x-pagination-next` a browser
1913
+ * cannot read the cursor, and a cursor read (nuxt-ui-mongocamp `fetchAllDocuments`) ends after the first page without saying so.
1881
1914
  */
1882
1915
  private upgradeLegacyDefaults;
1883
1916
  /** Reads the stored values; at startup also the keys that need a restart, later only the ones that are active at once. */
@@ -1922,6 +1955,11 @@ interface InterceptorBase {
1922
1955
  databaseName: string;
1923
1956
  /** The user has an administrator role (2.3.0; set by the routes, absent in payloads built elsewhere). */
1924
1957
  isAdmin?: boolean;
1958
+ /**
1959
+ * The administrator who sent the request when it acts for `user` (2.7.0, header `X-AUTH-ACT-AS`); `user` and `isAdmin` are then the
1960
+ * ones of the user it acts for.
1961
+ */
1962
+ actedBy?: UserInformation;
1925
1963
  }
1926
1964
  interface WriteInterceptorPayloads {
1927
1965
  /** Documents to insert: one for `PUT …/documents`, all of the request for `insertMany`, one batch for an import. */
@@ -2903,8 +2941,8 @@ interface WriteStamp {
2903
2941
  now: Date;
2904
2942
  userId: string;
2905
2943
  }
2906
- /** Sets the creation and change fields of a new document. */
2907
- declare function stampInsert(document: Document$2, timestamps: Timestamps, stamp: WriteStamp): void;
2944
+ /** Sets the creation and change fields of a new document; with `keepSent` the fields the document already has stay. */
2945
+ declare function stampInsert(document: Document$2, timestamps: Timestamps, stamp: WriteStamp, keepSent?: boolean): void;
2908
2946
  /**
2909
2947
  * Sets the change fields of a replacing document; the creation fields stay as stored (put back by the guard), a document without them
2910
2948
  * (stored before the behaviour was switched on) gets the values of this write.
@@ -2913,5 +2951,5 @@ declare function stampReplace(document: Document$2, timestamps: Timestamps, stam
2913
2951
  /** An update with the change fields set (`$set` with dot paths, so the creation fields next to them stay). */
2914
2952
  declare function stampUpdate(update: Document$2, timestamps: Timestamps, stamp: WriteStamp): Document$2;
2915
2953
 
2916
- export { AuditCollection, AuthService, AuthorizedUser, BehaviourDefaults, CleanUpTokenJob, CleanUpTokenJobClass, CollectionRegistry, ConfigKeys, ConfigPersistence, ConfigStore, ConfigurationError, DefaultRowsPerPage, DefaultValidationMode, DocumentService, ErrorCodes, EventBus, FilterDefaultField, HookPrefix, InfoCache, InternalErrorMessage, JobScheduler, LuceneQueryError, MaxExpands, MongocampDatabase, MongocampError, MongocampMetrics, OwnIndexPrefix, PaginationHeaders, SyncValidationLevel, SystemUser, TextMarker, WriteInterceptors, auditCollectionOf, auditRecords, bsonMarkerOptions, collections, combineScopes, configDefinitions, connectHooks, consoleLogger, convertFields, convertIdValue, createMongocampServer, createServerCollection, decodeAny, defineMongocampCollection, documentToJson, ensureAuditIndexes, filterParameter, forwardEventsToHooks, forwardInterceptorsToHooks, guardedPaths, luceneQueryToFilter, luceneToFilter, metrics, notDeleted, ownedBy, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, purgeIndexName, readScope, refsOf, requestFields, requestLogging, resolveBehaviours, resolveIndexes, resolveRefs, restoreUpdate, sameValidator, stampInsert, stampReplace, stampUpdate, stringifyJson, stripDocument, stripUpdate, syncIndexes, syncPurgeIndex, syncValidator, systemFields, toErrorResponse, toMongoJsonSchema, validatorOf, versionInDocument, versionInUpdate, withDeletedOf, withIncrement, withSystemFields, withVersion };
2954
+ export { ActAsHeader, AuditCollection, AuthService, AuthorizedUser, BehaviourDefaults, CleanUpTokenJob, CleanUpTokenJobClass, CollectionRegistry, ConfigKeys, ConfigPersistence, ConfigStore, ConfigurationError, DefaultRowsPerPage, DefaultValidationMode, DocumentService, ErrorCodes, EventBus, FilterDefaultField, HookPrefix, InfoCache, InternalErrorMessage, JobScheduler, LuceneQueryError, MaxExpands, MongocampDatabase, MongocampError, MongocampMetrics, OwnIndexPrefix, PaginationHeaders, SyncValidationLevel, SystemUser, TextMarker, WriteInterceptors, auditCollectionOf, auditRecords, bsonMarkerOptions, collections, combineScopes, configDefinitions, connectHooks, consoleLogger, convertFields, convertIdValue, createMongocampServer, createServerCollection, decodeAny, defineMongocampCollection, documentToJson, ensureAuditIndexes, filterParameter, forwardEventsToHooks, forwardInterceptorsToHooks, guardedPaths, luceneQueryToFilter, luceneToFilter, metrics, notDeleted, ownedBy, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, purgeIndexName, readScope, refsOf, requestFields, requestLogging, resolveBehaviours, resolveIndexes, resolveRefs, restoreUpdate, sameValidator, stampInsert, stampReplace, stampUpdate, stringifyJson, stripDocument, stripUpdate, syncIndexes, syncPurgeIndex, syncValidator, systemFields, toErrorResponse, toMongoJsonSchema, validatorOf, versionInDocument, versionInUpdate, withDeletedOf, withIncrement, withSystemFields, withVersion };
2917
2955
  export type { AuditOperation, AuditOptions, AuditRecord, BehaviourFlags, ConfigDefinition, ConfigKey, ConfigType, ConversionResult, ConvertOptions, DeclaredCollection, ErrorDescription, ErrorResponseOptions, EventListener, EventName, EventTarget, ExpandedDocument, ExtendedJsonMode, FetchOptions, Grant, HookSystem, IndexDeclaration, IndexDirection, IndexOptions, IndexSyncResult, InferDocument, InferDocumentInput, InferRefs, InterceptorBase, InterceptorName, InterceptorStage, InterceptorTarget, JobConfig, JobHandler, JobInformation, JobRun, LuceneQuery, MongocampCollectionDefinition, MongocampContext, MongocampEvent, MongocampEvents, MongocampFeature, MongocampHooks, MongocampLogger, MongocampRequestFields, MongocampServer, MongocampServerOptions, OwnerOptions, PaginationInfo, Paging, ReadOperation, ReadScope, RefDeclaration, RefTargets, RequestLog, ResolvedBehaviours, ResolvedIndex, ResolvedRef, Role, ScopeOptions, ServerCollection, ServerCollectionOptions, ServerCollectionUser, ServerDocumentIdentity, ServerFindOptions, ServerPage, SoftDeleteOptions, SystemFields, SystemInfo, TimestampsOptions, UserInformation, ValidationIssue, ValidationMode, ValidatorSyncAction, ValidatorSyncResult, VersionInfo, VersionedOptions, WriteInterceptor, WriteInterceptorPayloads, WriteStamp };
package/dist/index.mjs CHANGED
@@ -37,17 +37,33 @@ function mergeGrants(roles) {
37
37
  return [...merged.values()].sort((a, b) => a.name.localeCompare(b.name) || a.grantType.localeCompare(b.grantType));
38
38
  }
39
39
  class AuthorizedUser {
40
- constructor(user, roles) {
40
+ constructor(user, roles, actingFor) {
41
41
  this.user = user;
42
42
  this.roles = roles;
43
43
  this.grants = mergeGrants(roles);
44
44
  this.isAdmin = roles.some((role) => role.isAdmin);
45
+ if (actingFor !== void 0) {
46
+ this.actingFor = actingFor;
47
+ }
45
48
  }
46
49
  grants;
47
50
  isAdmin;
51
+ /**
52
+ * The user an administrator acts for (2.7.0, header `X-AUTH-ACT-AS`): the rights of the request stay the administrator's, but the
53
+ * behaviours (owner, timestamps, versioned, audit), the read scopes and the events see this user.
54
+ */
55
+ actingFor;
48
56
  get userId() {
49
57
  return this.user.userId;
50
58
  }
59
+ /** The user the request acts for: the one of `X-AUTH-ACT-AS`, else the logged in user itself. */
60
+ get acting() {
61
+ return this.actingFor ?? this;
62
+ }
63
+ /** This user acting for another one (2.7.0). */
64
+ actingAs(other) {
65
+ return new AuthorizedUser(this.user, this.roles, other);
66
+ }
51
67
  /** Collection grants, and the bucket meta grants as grants for the `.files` collection of the bucket. */
52
68
  get collectionGrants() {
53
69
  const collection = this.grants.filter((grant) => equalsIgnoreCase(grant.grantType, GrantTypes.collection));
@@ -88,6 +104,12 @@ class AuthorizedUser {
88
104
  return toUserProfile(this.user, this.roles);
89
105
  }
90
106
  }
107
+ function actingUser(user) {
108
+ return user.actingFor === void 0 ? { user: user.user } : { user: user.actingFor.user, actedBy: user.user };
109
+ }
110
+ function actingIdentity(user) {
111
+ return { ...actingUser(user), isAdmin: user.acting.isAdmin };
112
+ }
91
113
  function toUserProfile(user, roles) {
92
114
  return {
93
115
  user: user.userId,
@@ -1575,6 +1597,7 @@ class TokenCache {
1575
1597
  }
1576
1598
 
1577
1599
  const ApiKeyHeader = "X-AUTH-APIKEY";
1600
+ const ActAsHeader = "X-AUTH-ACT-AS";
1578
1601
  function readCredentials(request) {
1579
1602
  const credentials = {};
1580
1603
  const authorization = request.headers.get("authorization")?.trim();
@@ -1668,7 +1691,15 @@ class AuthService {
1668
1691
  async authenticate(request) {
1669
1692
  const user = await this.authenticateUser(readCredentials(request));
1670
1693
  this.requestUsers.set(request, user.userId);
1671
- return new AuthorizedUser(user, await this.holder.findRoles(user.roles));
1694
+ const authorized = new AuthorizedUser(user, await this.holder.findRoles(user.roles));
1695
+ const actAs = request.headers.get(ActAsHeader)?.trim();
1696
+ if (actAs === void 0 || actAs === "") {
1697
+ return authorized;
1698
+ }
1699
+ if (!authorized.isAdmin) {
1700
+ throw this.grantDenied(`only an administrator can act for another user (${ActAsHeader})`);
1701
+ }
1702
+ return authorized.actingAs(await this.authorizedUser(actAs));
1672
1703
  }
1673
1704
  /** The id of the user a request was authenticated as, `undefined` before (or without) the authentication. */
1674
1705
  userOf(request) {
@@ -1937,6 +1968,11 @@ class ConfigStore {
1937
1968
  const EnvComment = "updated by env";
1938
1969
  const SecretKeys = /* @__PURE__ */ new Set(["CONNECTION_PASSWORD", "AUTH_SECRET"]);
1939
1970
  const SecretMask = "********";
1971
+ const LegacyCorsHeadersExposed = [
1972
+ ["Content-Type", "x-pagination-rows-per-page", "x-pagination-current-page", "x-pagination-count-rows", "x-pagination-count-pages"],
1973
+ ["Content-Type", "x-pagination-rows-per-page", "x-pagination-current-page", "x-pagination-count-rows", "x-pagination-count-pages", "x-request-id"],
1974
+ ["Content-Type", "x-pagination-rows-per-page", "x-pagination-current-page", "x-pagination-count-rows", "x-pagination-count-pages", "x-pagination-next", "x-request-id"]
1975
+ ];
1940
1976
  const RefreshIntervalMillis = 6e4;
1941
1977
  function plainNumber(value) {
1942
1978
  if (typeof value === "number") {
@@ -2038,9 +2074,19 @@ class ConfigPersistence {
2038
2074
  * 2.6.0: a database created before 2.2.0 stored the old default 401 of `AUTH_GRANT_DENIED_STATUS` at its first start, and kept answering
2039
2075
  * 401 for a missing grant. A stored 401 that no update set (no `changedAt`, written since 2.6.0) becomes the default 403 once; an
2040
2076
  * administrator who wants 401 patches it again (then it is marked and stays).
2077
+ *
2078
+ * 2.7.1: the same for an old default of `CORS_HEADERS_EXPOSED` (see `LegacyCorsHeadersExposed`). Without `x-pagination-next` a browser
2079
+ * cannot read the cursor, and a cursor read (nuxt-ui-mongocamp `fetchAllDocuments`) ends after the first page without saying so.
2041
2080
  */
2042
2081
  async upgradeLegacyDefaults() {
2043
2082
  await this.collection.updateOne({ key: "AUTH_GRANT_DENIED_STATUS", value: 401, changedAt: { $exists: false } }, { $set: { value: 403 } });
2083
+ const corsHeadersExposed = this.config.definition(ConfigKeys.CorsHeadersExposed);
2084
+ if (corsHeadersExposed) {
2085
+ await this.collection.updateOne(
2086
+ { key: corsHeadersExposed.key, value: { $in: LegacyCorsHeadersExposed }, changedAt: { $exists: false } },
2087
+ { $set: { value: toStored(corsHeadersExposed.type, defaultOf(corsHeadersExposed)) } }
2088
+ );
2089
+ }
2044
2090
  }
2045
2091
  /** Reads the stored values; at startup also the keys that need a restart, later only the ones that are active at once. */
2046
2092
  async refresh(startup) {
@@ -2817,8 +2863,8 @@ const BehaviourDefaults = {
2817
2863
  auditRetentionDays: 365
2818
2864
  };
2819
2865
  const optionKeys = {
2820
- timestamps: ["createdAt", "updatedAt", "createdBy", "updatedBy"],
2821
- owner: ["field", "read", "adminBypass"],
2866
+ timestamps: ["createdAt", "updatedAt", "createdBy", "updatedBy", "preserveOnInsert"],
2867
+ owner: ["field", "read", "adminBypass", "preserveOnInsert"],
2822
2868
  softDelete: ["field", "purgeAfterDays"],
2823
2869
  versioned: ["mode", "field", "required"],
2824
2870
  audit: ["retentionDays"]
@@ -2874,6 +2920,14 @@ function resolveBehaviours(flags) {
2874
2920
  ...timestamps.createdBy !== void 0 ? { createdBy: field(timestamps.createdBy, BehaviourDefaults.createdBy, "timestamps.createdBy") } : {},
2875
2921
  ...timestamps.updatedBy !== void 0 ? { updatedBy: field(timestamps.updatedBy, BehaviourDefaults.updatedBy, "timestamps.updatedBy") } : {}
2876
2922
  };
2923
+ if (timestamps.preserveOnInsert !== void 0) {
2924
+ if (typeof timestamps.preserveOnInsert !== "boolean") {
2925
+ throw new TypeError("timestamps.preserveOnInsert must be true or false");
2926
+ }
2927
+ if (timestamps.preserveOnInsert) {
2928
+ resolved.timestamps.preserveOnInsert = true;
2929
+ }
2930
+ }
2877
2931
  }
2878
2932
  const owner = options(flags.owner, "owner");
2879
2933
  if (owner !== void 0) {
@@ -2889,6 +2943,14 @@ function resolveBehaviours(flags) {
2889
2943
  read,
2890
2944
  adminBypass: owner.adminBypass ?? true
2891
2945
  };
2946
+ if (owner.preserveOnInsert !== void 0) {
2947
+ if (typeof owner.preserveOnInsert !== "boolean") {
2948
+ throw new TypeError("owner.preserveOnInsert must be true or false");
2949
+ }
2950
+ if (owner.preserveOnInsert) {
2951
+ resolved.owner.preserveOnInsert = true;
2952
+ }
2953
+ }
2892
2954
  }
2893
2955
  const softDelete = options(flags.softDelete, "softDelete");
2894
2956
  if (softDelete !== void 0) {
@@ -2934,6 +2996,18 @@ function resolveBehaviours(flags) {
2934
2996
  checkOverlaps(resolved);
2935
2997
  return resolved;
2936
2998
  }
2999
+ function timestampPaths(timestamps) {
3000
+ return [timestamps.createdAt, timestamps.updatedAt, timestamps.createdBy, timestamps.updatedBy].filter((path) => path !== void 0);
3001
+ }
3002
+ function byAdministrator(event) {
3003
+ return event.isAdmin === true || event.actedBy !== void 0;
3004
+ }
3005
+ function preservesOnInsert(timestamps, event) {
3006
+ return timestamps?.preserveOnInsert === true && byAdministrator(event);
3007
+ }
3008
+ function preservesOwnerOnInsert(owner, event) {
3009
+ return owner?.preserveOnInsert === true && byAdministrator(event);
3010
+ }
2937
3011
  function systemFields(behaviours) {
2938
3012
  const fields = [];
2939
3013
  const { timestamps, owner, softDelete, versioned } = behaviours;
@@ -3628,7 +3702,13 @@ function registerGuard(context, own) {
3628
3702
  context.interceptors.on("document:beforeInsert", (event) => {
3629
3703
  const guard = guardedFor(event.collectionName);
3630
3704
  if (guard !== void 0) {
3631
- event.documents = event.documents.map((document) => stripDocument(document, guard.all));
3705
+ const { timestamps, owner } = guard.declared.behaviours;
3706
+ const kept = [
3707
+ ...timestamps !== void 0 && preservesOnInsert(timestamps, event) ? timestampPaths(timestamps) : [],
3708
+ ...owner !== void 0 && preservesOwnerOnInsert(owner, event) ? [owner.field] : []
3709
+ ];
3710
+ const stripped = guard.all.filter((path) => !kept.includes(path));
3711
+ event.documents = event.documents.map((document) => stripDocument(document, stripped));
3632
3712
  }
3633
3713
  }, { stage: "guard" }),
3634
3714
  context.interceptors.on("document:beforeReplace", async (event) => {
@@ -3768,8 +3848,11 @@ function registerOwner(context, own) {
3768
3848
  context.interceptors.on("document:beforeInsert", (event) => {
3769
3849
  const found = declaredFor(event.collectionName);
3770
3850
  if (found !== void 0 && found.owner.field !== found.behaviours.timestamps?.createdBy) {
3851
+ const keepSent = preservesOwnerOnInsert(found.owner, event);
3771
3852
  for (const document of event.documents) {
3772
- setPath(document, found.owner.field, event.user.userId);
3853
+ if (!keepSent || getPath(document, found.owner.field) === void 0) {
3854
+ setPath(document, found.owner.field, event.user.userId);
3855
+ }
3773
3856
  }
3774
3857
  }
3775
3858
  }, { stage: "system" }),
@@ -3800,14 +3883,19 @@ function registerOwner(context, own) {
3800
3883
  };
3801
3884
  }
3802
3885
 
3803
- function stampInsert(document, timestamps, stamp) {
3804
- setPath(document, timestamps.createdAt, stamp.now);
3805
- setPath(document, timestamps.updatedAt, stamp.now);
3886
+ function stampInsert(document, timestamps, stamp, keepSent = false) {
3887
+ const write = (path, value) => {
3888
+ if (!keepSent || getPath(document, path) === void 0) {
3889
+ setPath(document, path, value);
3890
+ }
3891
+ };
3892
+ write(timestamps.createdAt, stamp.now);
3893
+ write(timestamps.updatedAt, stamp.now);
3806
3894
  if (timestamps.createdBy !== void 0) {
3807
- setPath(document, timestamps.createdBy, stamp.userId);
3895
+ write(timestamps.createdBy, stamp.userId);
3808
3896
  }
3809
3897
  if (timestamps.updatedBy !== void 0) {
3810
- setPath(document, timestamps.updatedBy, stamp.userId);
3898
+ write(timestamps.updatedBy, stamp.userId);
3811
3899
  }
3812
3900
  }
3813
3901
  function stampReplace(document, timestamps, stamp) {
@@ -3841,8 +3929,9 @@ function registerTimestamps(context, own, clock = () => /* @__PURE__ */ new Date
3841
3929
  const timestamps = timestampsFor(event.collectionName);
3842
3930
  if (timestamps !== void 0) {
3843
3931
  const stamp = stampOf(event.user);
3932
+ const keepSent = preservesOnInsert(timestamps, event);
3844
3933
  for (const document of event.documents) {
3845
- stampInsert(document, timestamps, stamp);
3934
+ stampInsert(document, timestamps, stamp, keepSent);
3846
3935
  }
3847
3936
  }
3848
3937
  }, { stage: "system" }),
@@ -5144,7 +5233,7 @@ async function readScopeParts(context, user, collection, filter, operation, opti
5144
5233
  return { filter, scope: {} };
5145
5234
  }
5146
5235
  const databaseName = databaseOf(context.database, parseCollectionName(collection)).databaseName;
5147
- const payload = await context.interceptors.run("document:beforeRead", { user: user.user, isAdmin: user.isAdmin, collectionName: collection, databaseName, filter, operation, scopes: [], withDeleted: options.withDeleted === true });
5236
+ const payload = await context.interceptors.run("document:beforeRead", { ...actingIdentity(user), collectionName: collection, databaseName, filter, operation, scopes: [], withDeleted: options.withDeleted === true });
5148
5237
  return { filter: combineScopes(filter, payload.scopes), scope: combineScopes({}, payload.scopes) };
5149
5238
  }
5150
5239
  function withDeletedOf(params, user, collection) {
@@ -5348,10 +5437,10 @@ class DocumentService {
5348
5437
  intercept(name, user, collection, fields) {
5349
5438
  const { interceptors, database } = this.context;
5350
5439
  if (!interceptors.has(name)) {
5351
- return Promise.resolve({ user: user.user, isAdmin: user.isAdmin, collectionName: collection, databaseName: "", ...fields });
5440
+ return Promise.resolve({ ...actingIdentity(user), collectionName: collection, databaseName: "", ...fields });
5352
5441
  }
5353
5442
  const databaseName = databaseOf(database, parseCollectionName(collection)).databaseName;
5354
- return interceptors.run(name, { user: user.user, isAdmin: user.isAdmin, collectionName: collection, databaseName, ...fields });
5443
+ return interceptors.run(name, { ...actingIdentity(user), collectionName: collection, databaseName, ...fields });
5355
5444
  }
5356
5445
  /**
5357
5446
  * The insert hooks: they may change the documents, but not their number (the errors of an insert and of an import name the documents by
@@ -5383,15 +5472,15 @@ class DocumentService {
5383
5472
  return { acknowledged: result.acknowledged, count: result.deletedCount };
5384
5473
  }
5385
5474
  inserted(user, collection, response, documents) {
5386
- this.context.events.publish("document:create", { user: user.user, collectionName: collection, insertResponse: response, ...documents !== void 0 ? { documents } : {} });
5475
+ this.context.events.publish("document:create", { ...actingUser(user), collectionName: collection, insertResponse: response, ...documents !== void 0 ? { documents } : {} });
5387
5476
  return response;
5388
5477
  }
5389
5478
  updated(user, collection, response, old, source) {
5390
- this.context.events.publish("document:update", { user: user.user, collectionName: collection, updateResponse: response, oldValues: old, source });
5479
+ this.context.events.publish("document:update", { ...actingUser(user), collectionName: collection, updateResponse: response, oldValues: old, source });
5391
5480
  return response;
5392
5481
  }
5393
5482
  deleted(user, collection, response, old, softDeleted) {
5394
- this.context.events.publish("document:delete", { user: user.user, collectionName: collection, deleteResponse: response, oldValues: old, ...softDeleted ? { softDeleted } : {} });
5483
+ this.context.events.publish("document:delete", { ...actingUser(user), collectionName: collection, deleteResponse: response, oldValues: old, ...softDeleted ? { softDeleted } : {} });
5395
5484
  return response;
5396
5485
  }
5397
5486
  /** Inserts one document (decoded). */
@@ -5433,7 +5522,7 @@ class DocumentService {
5433
5522
  const state = await importStream(this.collection(collection), body, maxBytes, beforeBatch);
5434
5523
  if (state.storedIds.length > 0) {
5435
5524
  const insertedIds = state.storedIdTexts;
5436
- this.context.events.publish("document:create", { user: user.user, collectionName: collection, insertResponse: { wasAcknowledged: true, insertedIds, insertedCount: insertedIds.length, errors: [] } });
5525
+ this.context.events.publish("document:create", { ...actingUser(user), collectionName: collection, insertResponse: { wasAcknowledged: true, insertedIds, insertedCount: insertedIds.length, errors: [] } });
5437
5526
  }
5438
5527
  return state;
5439
5528
  }
@@ -5502,12 +5591,12 @@ class DocumentService {
5502
5591
  }
5503
5592
  const filter = await this.scope(user, collection, pathIdFilter(id), "restore");
5504
5593
  const old = this.context.events.has("document:restore", collection) ? await this.collection(collection).find(filter).limit(1).toArray() : [];
5505
- const result = await this.collection(collection).updateOne(filter, restoreUpdate(declared.behaviours, { now: /* @__PURE__ */ new Date(), userId: user.user.userId }));
5594
+ const result = await this.collection(collection).updateOne(filter, restoreUpdate(declared.behaviours, { now: /* @__PURE__ */ new Date(), userId: user.acting.userId }));
5506
5595
  if (result.matchedCount === 0) {
5507
5596
  throw MongocampError.notFound("could not find a deleted document with this id");
5508
5597
  }
5509
5598
  const response = updateResponse(result, id);
5510
- this.context.events.publish("document:restore", { user: user.user, collectionName: collection, updateResponse: response, oldValues: old });
5599
+ this.context.events.publish("document:restore", { ...actingUser(user), collectionName: collection, updateResponse: response, oldValues: old });
5511
5600
  return response;
5512
5601
  }
5513
5602
  /** The audit records of a filter (a document or the collection), newest first. */
@@ -19521,4 +19610,4 @@ async function connectHooks(server, hooks) {
19521
19610
  };
19522
19611
  }
19523
19612
 
19524
- export { AuditCollection, AuthorizedUser, BehaviourDefaults, CleanUpTokenJob, CleanUpTokenJobClass, CollectionRegistry, ConfigKeys, ConfigStore, ConfigurationError, DefaultRowsPerPage, DefaultValidationMode, DocumentService, ErrorCodes, EventBus, FilterDefaultField, HookPrefix, InternalErrorMessage, JobScheduler, LuceneQueryError, MaxExpands, MongocampError, OwnIndexPrefix, PaginationHeaders, SyncValidationLevel, SystemUser, TextMarker, WriteInterceptors, auditCollectionOf, auditRecords, bsonMarkerOptions, collections, combineScopes, configDefinitions, connectHooks, consoleLogger, convertFields, convertIdValue, createMongocampServer, createServerCollection, decodeAny, defineMongocampCollection, documentToJson, ensureAuditIndexes, filterParameter, forwardEventsToHooks, forwardInterceptorsToHooks, guardedPaths, luceneQueryToFilter, luceneToFilter, metrics, notDeleted, ownedBy, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, purgeIndexName, readScope, refsOf, requestFields, requestLogging, resolveBehaviours, resolveIndexes, resolveRefs, restoreUpdate, sameValidator, stampInsert, stampReplace, stampUpdate, stringifyJson, stripDocument, stripUpdate, syncIndexes, syncPurgeIndex, syncValidator, systemFields, toErrorResponse, toMongoJsonSchema, validatorOf$1 as validatorOf, versionInDocument, versionInUpdate, withDeletedOf, withIncrement, withSystemFields, withVersion };
19613
+ export { ActAsHeader, AuditCollection, AuthorizedUser, BehaviourDefaults, CleanUpTokenJob, CleanUpTokenJobClass, CollectionRegistry, ConfigKeys, ConfigStore, ConfigurationError, DefaultRowsPerPage, DefaultValidationMode, DocumentService, ErrorCodes, EventBus, FilterDefaultField, HookPrefix, InternalErrorMessage, JobScheduler, LuceneQueryError, MaxExpands, MongocampError, OwnIndexPrefix, PaginationHeaders, SyncValidationLevel, SystemUser, TextMarker, WriteInterceptors, auditCollectionOf, auditRecords, bsonMarkerOptions, collections, combineScopes, configDefinitions, connectHooks, consoleLogger, convertFields, convertIdValue, createMongocampServer, createServerCollection, decodeAny, defineMongocampCollection, documentToJson, ensureAuditIndexes, filterParameter, forwardEventsToHooks, forwardInterceptorsToHooks, guardedPaths, luceneQueryToFilter, luceneToFilter, metrics, notDeleted, ownedBy, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, purgeIndexName, readScope, refsOf, requestFields, requestLogging, resolveBehaviours, resolveIndexes, resolveRefs, restoreUpdate, sameValidator, stampInsert, stampReplace, stampUpdate, stringifyJson, stripDocument, stripUpdate, syncIndexes, syncPurgeIndex, syncValidator, systemFields, toErrorResponse, toMongoJsonSchema, validatorOf$1 as validatorOf, versionInDocument, versionInUpdate, withDeletedOf, withIncrement, withSystemFields, withVersion };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sfxcode/mongocamp-server-core",
3
- "version": "2.6.1",
3
+ "version": "2.7.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {