@rebasepro/server-mongo 0.27.0 → 0.28.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.
@@ -68,7 +68,12 @@ export declare class MongoPasswordResetTokenService {
68
68
  uid: string;
69
69
  expiresAt: Date;
70
70
  } | null>;
71
- markAsUsed(tokenHash: string): Promise<void>;
71
+ /**
72
+ * Mark the token used if it is still valid, and say whether this call did.
73
+ * The filter is the validity check, so of two requests presenting the same
74
+ * token only one modifies it.
75
+ */
76
+ markAsUsed(tokenHash: string): Promise<boolean>;
72
77
  deleteAllForUser(uid: string): Promise<void>;
73
78
  deleteExpired(): Promise<void>;
74
79
  }
@@ -90,12 +95,14 @@ export declare class MongoTokenRepository implements TokenRepository {
90
95
  deleteRefreshTokenById(id: string, uid: string): Promise<void>;
91
96
  createPasswordResetToken(uid: string, tokenHash: string, expiresAt: Date): Promise<void>;
92
97
  findValidPasswordResetToken(tokenHash: string): Promise<PasswordResetTokenInfo | null>;
93
- markPasswordResetTokenUsed(tokenHash: string): Promise<void>;
98
+ markPasswordResetTokenUsed(tokenHash: string): Promise<boolean>;
94
99
  deleteAllPasswordResetTokensForUser(uid: string): Promise<void>;
95
100
  deleteExpiredTokens(): Promise<void>;
96
101
  createMagicLinkToken(uid: string, tokenHash: string, expiresAt: Date): Promise<void>;
97
102
  findValidMagicLinkToken(tokenHash: string): Promise<MagicLinkTokenInfo | null>;
98
- markMagicLinkTokenUsed(tokenHash: string): Promise<void>;
103
+ /** As {@link MongoPasswordResetTokenService.markAsUsed}: `true` only for the call that consumed it. */
104
+ markMagicLinkTokenUsed(tokenHash: string): Promise<boolean>;
105
+ deleteAllMagicLinkTokensForUser(uid: string): Promise<void>;
99
106
  }
100
107
  export declare class MongoAuthRepository implements AuthRepository {
101
108
  private db;
@@ -136,12 +143,13 @@ export declare class MongoAuthRepository implements AuthRepository {
136
143
  deleteRefreshTokenById(id: string, uid: string): Promise<void>;
137
144
  createPasswordResetToken(uid: string, tokenHash: string, expiresAt: Date): Promise<void>;
138
145
  findValidPasswordResetToken(tokenHash: string): Promise<PasswordResetTokenInfo | null>;
139
- markPasswordResetTokenUsed(tokenHash: string): Promise<void>;
146
+ markPasswordResetTokenUsed(tokenHash: string): Promise<boolean>;
140
147
  deleteAllPasswordResetTokensForUser(uid: string): Promise<void>;
141
148
  deleteExpiredTokens(): Promise<void>;
142
149
  createMagicLinkToken(uid: string, tokenHash: string, expiresAt: Date): Promise<void>;
143
150
  findValidMagicLinkToken(tokenHash: string): Promise<MagicLinkTokenInfo | null>;
144
- markMagicLinkTokenUsed(tokenHash: string): Promise<void>;
151
+ markMagicLinkTokenUsed(tokenHash: string): Promise<boolean>;
152
+ deleteAllMagicLinkTokensForUser(uid: string): Promise<void>;
145
153
  createMfaFactor(uid: string, factorType: "totp", secretEncrypted: string, friendlyName?: string): Promise<MfaFactor>;
146
154
  getMfaFactors(uid: string): Promise<MfaFactor[]>;
147
155
  getMfaFactorById(factorId: string): Promise<(MfaFactor & {
package/dist/index.es.js CHANGED
@@ -103,6 +103,20 @@ function likePatternToRegExp(pattern, caseInsensitive) {
103
103
  return new RegExp(`^${body}$`, caseInsensitive ? "i" : "");
104
104
  }
105
105
  /**
106
+ * Refuse a filter column that Mongo would read as an operator.
107
+ *
108
+ * The column is the key of the condition this builder emits, so a column of
109
+ * `$expr` turns `[">", ["$salary", 100000]]` into
110
+ * `{ $expr: { $gt: ["$salary", 100000] } }` — an aggregation expression over
111
+ * any field of the document, the withheld ones included, and through
112
+ * `$function` a way to run JavaScript on the database. No document field a
113
+ * collection declares is spelled with a `$`, on any segment of its path.
114
+ */
115
+ function assertFieldPath(field) {
116
+ if (typeof field === "string" && field !== "" && !field.split(".").some((segment) => segment.startsWith("$"))) return;
117
+ throw ApiError.badRequest(`${JSON.stringify(field)} is not a field a filter can name on the MongoDB driver.`, "UNKNOWN_FILTER_FIELD", { field });
118
+ }
119
+ /**
106
120
  * MongoDB Condition Builder
107
121
  *
108
122
  * Provides static methods to translate Rebase filter conditions
@@ -144,6 +158,7 @@ var MongoConditionBuilder = class MongoConditionBuilder {
144
158
  * The null tests are never unknown, and negate to each other.
145
159
  */
146
160
  static buildCondition(field, op, value, negated = false) {
161
+ assertFieldPath(field);
147
162
  if (op === "is-null" || op === "is-not-null") {
148
163
  const isNull = op === "is-null" !== negated;
149
164
  return { [field]: isNull ? { $eq: null } : { $ne: null } };
@@ -1204,6 +1219,15 @@ var MATCH_ALL = {};
1204
1219
  * {@link isMatchNone} tests, so never mutate or copy it.
1205
1220
  */
1206
1221
  var MATCH_NONE = { _id: { $exists: false } };
1222
+ /**
1223
+ * Matches no document, for a comparison SQL answers with NULL — one against a
1224
+ * NULL value. NULL denies a row exactly as `false` does, so this is a filter
1225
+ * like {@link MATCH_NONE}; it is a distinct object because the two part ways
1226
+ * under `not`: `NOT false` is true, `NOT NULL` is still NULL. Neither
1227
+ * {@link isMatchAll} nor {@link isMatchNone} recognises it, so a negation over
1228
+ * it is refused rather than folded into "match every document".
1229
+ */
1230
+ var MATCH_UNKNOWN = { _id: { $exists: false } };
1207
1231
  /** The expression has no MongoDB equivalent — the caller must refuse. */
1208
1232
  var UNTRANSLATABLE = "untranslatable";
1209
1233
  function isMatchAll(f) {
@@ -1346,9 +1370,14 @@ function policyToMongoFilter(expr, user) {
1346
1370
  const left = resolveOperand(expr.left, ctx);
1347
1371
  const right = resolveOperand(expr.right, ctx);
1348
1372
  if (left.kind === "unknown" || right.kind === "unknown") return UNTRANSLATABLE;
1349
- if (left.kind === "field" && right.kind === "value") return { [left.name]: { [COMPARE_TO_MONGO[expr.op]]: right.value } };
1350
- if (left.kind === "value" && right.kind === "field") return { [right.name]: { [COMPARE_TO_MONGO[INVERTED_COMPARE[expr.op]]]: left.value } };
1351
- if (left.kind === "field" && right.kind === "field") return { $expr: { [COMPARE_TO_MONGO[expr.op]]: [`$${left.name}`, `$${right.name}`] } };
1373
+ if (left.kind === "value" && left.value == null || right.kind === "value" && right.value == null) return MATCH_UNKNOWN;
1374
+ if (left.kind === "field" && right.kind === "value") return compareField(left.name, expr.op, right.value);
1375
+ if (left.kind === "value" && right.kind === "field") return compareField(right.name, INVERTED_COMPARE[expr.op], left.value);
1376
+ if (left.kind === "field" && right.kind === "field") return { $and: [
1377
+ { [left.name]: { $ne: null } },
1378
+ { [right.name]: { $ne: null } },
1379
+ { $expr: { [COMPARE_TO_MONGO[expr.op]]: [`$${left.name}`, `$${right.name}`] } }
1380
+ ] };
1352
1381
  if (left.kind === "value" && right.kind === "value") return compareValues(expr.op, left.value, right.value);
1353
1382
  return UNTRANSLATABLE;
1354
1383
  }
@@ -1361,6 +1390,18 @@ function policyToMongoFilter(expr, user) {
1361
1390
  case "raw": return UNTRANSLATABLE;
1362
1391
  }
1363
1392
  }
1393
+ /**
1394
+ * `field <op> value` for a value that is not null. Only `$ne` needs more than
1395
+ * the operator: it is the one that matches a document whose field is null or
1396
+ * missing, where SQL's `<>` is NULL.
1397
+ */
1398
+ function compareField(name, op, value) {
1399
+ if (op === "neq") return { [name]: {
1400
+ $ne: value,
1401
+ $nin: [null]
1402
+ } };
1403
+ return { [name]: { [COMPARE_TO_MONGO[op]]: value } };
1404
+ }
1364
1405
  function compareValues(op, a, b) {
1365
1406
  if (op === "eq") return a === b ? MATCH_ALL : MATCH_NONE;
1366
1407
  if (op === "neq") return a !== b ? MATCH_ALL : MATCH_NONE;
@@ -2176,7 +2217,9 @@ function assertQueryFieldsReadable(props, collection, viewer) {
2176
2217
  if (refused.size === 0) return;
2177
2218
  const named = /* @__PURE__ */ new Set();
2178
2219
  const consider = (field) => {
2179
- if (typeof field === "string" && refused.has(field)) named.add(field);
2220
+ if (typeof field !== "string") return;
2221
+ const head = field.split(".")[0];
2222
+ if (refused.has(head)) named.add(head);
2180
2223
  };
2181
2224
  Object.keys(props.filter ?? {}).forEach(consider);
2182
2225
  const walk = (logical) => {
@@ -2871,8 +2914,18 @@ var MongoPasswordResetTokenService = class {
2871
2914
  expiresAt: new Date(doc.expiresAt)
2872
2915
  };
2873
2916
  }
2917
+ /**
2918
+ * Mark the token used if it is still valid, and say whether this call did.
2919
+ * The filter is the validity check, so of two requests presenting the same
2920
+ * token only one modifies it.
2921
+ */
2874
2922
  async markAsUsed(tokenHash) {
2875
- await this.collection.updateOne({ tokenHash }, { $set: { usedAt: /* @__PURE__ */ new Date() } });
2923
+ const now = /* @__PURE__ */ new Date();
2924
+ return (await this.collection.updateOne({
2925
+ tokenHash,
2926
+ usedAt: null,
2927
+ expiresAt: { $gt: now }
2928
+ }, { $set: { usedAt: now } })).modifiedCount > 0;
2876
2929
  }
2877
2930
  async deleteAllForUser(uid) {
2878
2931
  await this.collection.deleteMany({ uid });
@@ -2930,7 +2983,7 @@ var MongoTokenRepository = class {
2930
2983
  return this.passwordResetTokenService.findValidByHash(tokenHash);
2931
2984
  }
2932
2985
  async markPasswordResetTokenUsed(tokenHash) {
2933
- await this.passwordResetTokenService.markAsUsed(tokenHash);
2986
+ return this.passwordResetTokenService.markAsUsed(tokenHash);
2934
2987
  }
2935
2988
  async deleteAllPasswordResetTokensForUser(uid) {
2936
2989
  await this.passwordResetTokenService.deleteAllForUser(uid);
@@ -2964,8 +3017,18 @@ var MongoTokenRepository = class {
2964
3017
  expiresAt: doc.expiresAt
2965
3018
  };
2966
3019
  }
3020
+ /** As {@link MongoPasswordResetTokenService.markAsUsed}: `true` only for the call that consumed it. */
2967
3021
  async markMagicLinkTokenUsed(tokenHash) {
2968
- await this.db.collection("magic_link_tokens").updateOne({ tokenHash }, { $set: { usedAt: /* @__PURE__ */ new Date() } });
3022
+ const col = this.db.collection("magic_link_tokens");
3023
+ const now = /* @__PURE__ */ new Date();
3024
+ return (await col.updateOne({
3025
+ tokenHash,
3026
+ usedAt: null,
3027
+ expiresAt: { $gt: now }
3028
+ }, { $set: { usedAt: now } })).modifiedCount > 0;
3029
+ }
3030
+ async deleteAllMagicLinkTokensForUser(uid) {
3031
+ await this.db.collection("magic_link_tokens").deleteMany({ uid });
2969
3032
  }
2970
3033
  };
2971
3034
  var MongoAuthRepository = class {
@@ -3071,7 +3134,7 @@ var MongoAuthRepository = class {
3071
3134
  return this.tokenRepository.findValidPasswordResetToken(tokenHash);
3072
3135
  }
3073
3136
  async markPasswordResetTokenUsed(tokenHash) {
3074
- await this.tokenRepository.markPasswordResetTokenUsed(tokenHash);
3137
+ return this.tokenRepository.markPasswordResetTokenUsed(tokenHash);
3075
3138
  }
3076
3139
  async deleteAllPasswordResetTokensForUser(uid) {
3077
3140
  await this.tokenRepository.deleteAllPasswordResetTokensForUser(uid);
@@ -3086,7 +3149,10 @@ var MongoAuthRepository = class {
3086
3149
  return this.tokenRepository.findValidMagicLinkToken(tokenHash);
3087
3150
  }
3088
3151
  async markMagicLinkTokenUsed(tokenHash) {
3089
- await this.tokenRepository.markMagicLinkTokenUsed(tokenHash);
3152
+ return this.tokenRepository.markMagicLinkTokenUsed(tokenHash);
3153
+ }
3154
+ async deleteAllMagicLinkTokensForUser(uid) {
3155
+ await this.tokenRepository.deleteAllMagicLinkTokensForUser(uid);
3090
3156
  }
3091
3157
  async createMfaFactor(uid, factorType, secretEncrypted, friendlyName) {
3092
3158
  throw new ApiError(501, "MFA_NOT_SUPPORTED", "Multi-factor authentication is not implemented for the MongoDB backend, so a factor cannot be stored. Use a Postgres data source for accounts that need a second factor.");