@sfxcode/mongocamp-server-core 2.6.1 → 2.7.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/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`. */
@@ -1922,6 +1952,11 @@ interface InterceptorBase {
1922
1952
  databaseName: string;
1923
1953
  /** The user has an administrator role (2.3.0; set by the routes, absent in payloads built elsewhere). */
1924
1954
  isAdmin?: boolean;
1955
+ /**
1956
+ * 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
1957
+ * ones of the user it acts for.
1958
+ */
1959
+ actedBy?: UserInformation;
1925
1960
  }
1926
1961
  interface WriteInterceptorPayloads {
1927
1962
  /** Documents to insert: one for `PUT …/documents`, all of the request for `insertMany`, one batch for an import. */
@@ -2903,8 +2938,8 @@ interface WriteStamp {
2903
2938
  now: Date;
2904
2939
  userId: string;
2905
2940
  }
2906
- /** Sets the creation and change fields of a new document. */
2907
- declare function stampInsert(document: Document$2, timestamps: Timestamps, stamp: WriteStamp): void;
2941
+ /** Sets the creation and change fields of a new document; with `keepSent` the fields the document already has stay. */
2942
+ declare function stampInsert(document: Document$2, timestamps: Timestamps, stamp: WriteStamp, keepSent?: boolean): void;
2908
2943
  /**
2909
2944
  * Sets the change fields of a replacing document; the creation fields stay as stored (put back by the guard), a document without them
2910
2945
  * (stored before the behaviour was switched on) gets the values of this write.
@@ -2913,5 +2948,5 @@ declare function stampReplace(document: Document$2, timestamps: Timestamps, stam
2913
2948
  /** An update with the change fields set (`$set` with dot paths, so the creation fields next to them stay). */
2914
2949
  declare function stampUpdate(update: Document$2, timestamps: Timestamps, stamp: WriteStamp): Document$2;
2915
2950
 
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 };
2951
+ 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
2952
  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) {
@@ -2817,8 +2848,8 @@ const BehaviourDefaults = {
2817
2848
  auditRetentionDays: 365
2818
2849
  };
2819
2850
  const optionKeys = {
2820
- timestamps: ["createdAt", "updatedAt", "createdBy", "updatedBy"],
2821
- owner: ["field", "read", "adminBypass"],
2851
+ timestamps: ["createdAt", "updatedAt", "createdBy", "updatedBy", "preserveOnInsert"],
2852
+ owner: ["field", "read", "adminBypass", "preserveOnInsert"],
2822
2853
  softDelete: ["field", "purgeAfterDays"],
2823
2854
  versioned: ["mode", "field", "required"],
2824
2855
  audit: ["retentionDays"]
@@ -2874,6 +2905,14 @@ function resolveBehaviours(flags) {
2874
2905
  ...timestamps.createdBy !== void 0 ? { createdBy: field(timestamps.createdBy, BehaviourDefaults.createdBy, "timestamps.createdBy") } : {},
2875
2906
  ...timestamps.updatedBy !== void 0 ? { updatedBy: field(timestamps.updatedBy, BehaviourDefaults.updatedBy, "timestamps.updatedBy") } : {}
2876
2907
  };
2908
+ if (timestamps.preserveOnInsert !== void 0) {
2909
+ if (typeof timestamps.preserveOnInsert !== "boolean") {
2910
+ throw new TypeError("timestamps.preserveOnInsert must be true or false");
2911
+ }
2912
+ if (timestamps.preserveOnInsert) {
2913
+ resolved.timestamps.preserveOnInsert = true;
2914
+ }
2915
+ }
2877
2916
  }
2878
2917
  const owner = options(flags.owner, "owner");
2879
2918
  if (owner !== void 0) {
@@ -2889,6 +2928,14 @@ function resolveBehaviours(flags) {
2889
2928
  read,
2890
2929
  adminBypass: owner.adminBypass ?? true
2891
2930
  };
2931
+ if (owner.preserveOnInsert !== void 0) {
2932
+ if (typeof owner.preserveOnInsert !== "boolean") {
2933
+ throw new TypeError("owner.preserveOnInsert must be true or false");
2934
+ }
2935
+ if (owner.preserveOnInsert) {
2936
+ resolved.owner.preserveOnInsert = true;
2937
+ }
2938
+ }
2892
2939
  }
2893
2940
  const softDelete = options(flags.softDelete, "softDelete");
2894
2941
  if (softDelete !== void 0) {
@@ -2934,6 +2981,18 @@ function resolveBehaviours(flags) {
2934
2981
  checkOverlaps(resolved);
2935
2982
  return resolved;
2936
2983
  }
2984
+ function timestampPaths(timestamps) {
2985
+ return [timestamps.createdAt, timestamps.updatedAt, timestamps.createdBy, timestamps.updatedBy].filter((path) => path !== void 0);
2986
+ }
2987
+ function byAdministrator(event) {
2988
+ return event.isAdmin === true || event.actedBy !== void 0;
2989
+ }
2990
+ function preservesOnInsert(timestamps, event) {
2991
+ return timestamps?.preserveOnInsert === true && byAdministrator(event);
2992
+ }
2993
+ function preservesOwnerOnInsert(owner, event) {
2994
+ return owner?.preserveOnInsert === true && byAdministrator(event);
2995
+ }
2937
2996
  function systemFields(behaviours) {
2938
2997
  const fields = [];
2939
2998
  const { timestamps, owner, softDelete, versioned } = behaviours;
@@ -3628,7 +3687,13 @@ function registerGuard(context, own) {
3628
3687
  context.interceptors.on("document:beforeInsert", (event) => {
3629
3688
  const guard = guardedFor(event.collectionName);
3630
3689
  if (guard !== void 0) {
3631
- event.documents = event.documents.map((document) => stripDocument(document, guard.all));
3690
+ const { timestamps, owner } = guard.declared.behaviours;
3691
+ const kept = [
3692
+ ...timestamps !== void 0 && preservesOnInsert(timestamps, event) ? timestampPaths(timestamps) : [],
3693
+ ...owner !== void 0 && preservesOwnerOnInsert(owner, event) ? [owner.field] : []
3694
+ ];
3695
+ const stripped = guard.all.filter((path) => !kept.includes(path));
3696
+ event.documents = event.documents.map((document) => stripDocument(document, stripped));
3632
3697
  }
3633
3698
  }, { stage: "guard" }),
3634
3699
  context.interceptors.on("document:beforeReplace", async (event) => {
@@ -3768,8 +3833,11 @@ function registerOwner(context, own) {
3768
3833
  context.interceptors.on("document:beforeInsert", (event) => {
3769
3834
  const found = declaredFor(event.collectionName);
3770
3835
  if (found !== void 0 && found.owner.field !== found.behaviours.timestamps?.createdBy) {
3836
+ const keepSent = preservesOwnerOnInsert(found.owner, event);
3771
3837
  for (const document of event.documents) {
3772
- setPath(document, found.owner.field, event.user.userId);
3838
+ if (!keepSent || getPath(document, found.owner.field) === void 0) {
3839
+ setPath(document, found.owner.field, event.user.userId);
3840
+ }
3773
3841
  }
3774
3842
  }
3775
3843
  }, { stage: "system" }),
@@ -3800,14 +3868,19 @@ function registerOwner(context, own) {
3800
3868
  };
3801
3869
  }
3802
3870
 
3803
- function stampInsert(document, timestamps, stamp) {
3804
- setPath(document, timestamps.createdAt, stamp.now);
3805
- setPath(document, timestamps.updatedAt, stamp.now);
3871
+ function stampInsert(document, timestamps, stamp, keepSent = false) {
3872
+ const write = (path, value) => {
3873
+ if (!keepSent || getPath(document, path) === void 0) {
3874
+ setPath(document, path, value);
3875
+ }
3876
+ };
3877
+ write(timestamps.createdAt, stamp.now);
3878
+ write(timestamps.updatedAt, stamp.now);
3806
3879
  if (timestamps.createdBy !== void 0) {
3807
- setPath(document, timestamps.createdBy, stamp.userId);
3880
+ write(timestamps.createdBy, stamp.userId);
3808
3881
  }
3809
3882
  if (timestamps.updatedBy !== void 0) {
3810
- setPath(document, timestamps.updatedBy, stamp.userId);
3883
+ write(timestamps.updatedBy, stamp.userId);
3811
3884
  }
3812
3885
  }
3813
3886
  function stampReplace(document, timestamps, stamp) {
@@ -3841,8 +3914,9 @@ function registerTimestamps(context, own, clock = () => /* @__PURE__ */ new Date
3841
3914
  const timestamps = timestampsFor(event.collectionName);
3842
3915
  if (timestamps !== void 0) {
3843
3916
  const stamp = stampOf(event.user);
3917
+ const keepSent = preservesOnInsert(timestamps, event);
3844
3918
  for (const document of event.documents) {
3845
- stampInsert(document, timestamps, stamp);
3919
+ stampInsert(document, timestamps, stamp, keepSent);
3846
3920
  }
3847
3921
  }
3848
3922
  }, { stage: "system" }),
@@ -5144,7 +5218,7 @@ async function readScopeParts(context, user, collection, filter, operation, opti
5144
5218
  return { filter, scope: {} };
5145
5219
  }
5146
5220
  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 });
5221
+ const payload = await context.interceptors.run("document:beforeRead", { ...actingIdentity(user), collectionName: collection, databaseName, filter, operation, scopes: [], withDeleted: options.withDeleted === true });
5148
5222
  return { filter: combineScopes(filter, payload.scopes), scope: combineScopes({}, payload.scopes) };
5149
5223
  }
5150
5224
  function withDeletedOf(params, user, collection) {
@@ -5348,10 +5422,10 @@ class DocumentService {
5348
5422
  intercept(name, user, collection, fields) {
5349
5423
  const { interceptors, database } = this.context;
5350
5424
  if (!interceptors.has(name)) {
5351
- return Promise.resolve({ user: user.user, isAdmin: user.isAdmin, collectionName: collection, databaseName: "", ...fields });
5425
+ return Promise.resolve({ ...actingIdentity(user), collectionName: collection, databaseName: "", ...fields });
5352
5426
  }
5353
5427
  const databaseName = databaseOf(database, parseCollectionName(collection)).databaseName;
5354
- return interceptors.run(name, { user: user.user, isAdmin: user.isAdmin, collectionName: collection, databaseName, ...fields });
5428
+ return interceptors.run(name, { ...actingIdentity(user), collectionName: collection, databaseName, ...fields });
5355
5429
  }
5356
5430
  /**
5357
5431
  * 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 +5457,15 @@ class DocumentService {
5383
5457
  return { acknowledged: result.acknowledged, count: result.deletedCount };
5384
5458
  }
5385
5459
  inserted(user, collection, response, documents) {
5386
- this.context.events.publish("document:create", { user: user.user, collectionName: collection, insertResponse: response, ...documents !== void 0 ? { documents } : {} });
5460
+ this.context.events.publish("document:create", { ...actingUser(user), collectionName: collection, insertResponse: response, ...documents !== void 0 ? { documents } : {} });
5387
5461
  return response;
5388
5462
  }
5389
5463
  updated(user, collection, response, old, source) {
5390
- this.context.events.publish("document:update", { user: user.user, collectionName: collection, updateResponse: response, oldValues: old, source });
5464
+ this.context.events.publish("document:update", { ...actingUser(user), collectionName: collection, updateResponse: response, oldValues: old, source });
5391
5465
  return response;
5392
5466
  }
5393
5467
  deleted(user, collection, response, old, softDeleted) {
5394
- this.context.events.publish("document:delete", { user: user.user, collectionName: collection, deleteResponse: response, oldValues: old, ...softDeleted ? { softDeleted } : {} });
5468
+ this.context.events.publish("document:delete", { ...actingUser(user), collectionName: collection, deleteResponse: response, oldValues: old, ...softDeleted ? { softDeleted } : {} });
5395
5469
  return response;
5396
5470
  }
5397
5471
  /** Inserts one document (decoded). */
@@ -5433,7 +5507,7 @@ class DocumentService {
5433
5507
  const state = await importStream(this.collection(collection), body, maxBytes, beforeBatch);
5434
5508
  if (state.storedIds.length > 0) {
5435
5509
  const insertedIds = state.storedIdTexts;
5436
- this.context.events.publish("document:create", { user: user.user, collectionName: collection, insertResponse: { wasAcknowledged: true, insertedIds, insertedCount: insertedIds.length, errors: [] } });
5510
+ this.context.events.publish("document:create", { ...actingUser(user), collectionName: collection, insertResponse: { wasAcknowledged: true, insertedIds, insertedCount: insertedIds.length, errors: [] } });
5437
5511
  }
5438
5512
  return state;
5439
5513
  }
@@ -5502,12 +5576,12 @@ class DocumentService {
5502
5576
  }
5503
5577
  const filter = await this.scope(user, collection, pathIdFilter(id), "restore");
5504
5578
  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 }));
5579
+ const result = await this.collection(collection).updateOne(filter, restoreUpdate(declared.behaviours, { now: /* @__PURE__ */ new Date(), userId: user.acting.userId }));
5506
5580
  if (result.matchedCount === 0) {
5507
5581
  throw MongocampError.notFound("could not find a deleted document with this id");
5508
5582
  }
5509
5583
  const response = updateResponse(result, id);
5510
- this.context.events.publish("document:restore", { user: user.user, collectionName: collection, updateResponse: response, oldValues: old });
5584
+ this.context.events.publish("document:restore", { ...actingUser(user), collectionName: collection, updateResponse: response, oldValues: old });
5511
5585
  return response;
5512
5586
  }
5513
5587
  /** The audit records of a filter (a document or the collection), newest first. */
@@ -19521,4 +19595,4 @@ async function connectHooks(server, hooks) {
19521
19595
  };
19522
19596
  }
19523
19597
 
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 };
19598
+ 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.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {