@terreno/api 56.0.0-beta.0 → 56.0.0-beta.2

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.
Files changed (56) hide show
  1. package/CHANGELOG.md +2 -122
  2. package/LICENSE +21 -202
  3. package/dist/api.d.ts +3 -2
  4. package/dist/auth.js +21 -25
  5. package/dist/betterAuthSetup.d.ts +15 -1
  6. package/dist/betterAuthSetup.js +4 -6
  7. package/dist/configurationPlugin.js +2 -2
  8. package/dist/expressServer.js +11 -5
  9. package/dist/githubAuth.js +1 -4
  10. package/dist/plugins.d.ts +7 -6
  11. package/dist/plugins.js +24 -8
  12. package/dist/realtime/realtimeApp.d.ts +1 -1
  13. package/dist/realtime/realtimeApp.js +16 -8
  14. package/dist/realtime/types.d.ts +14 -0
  15. package/dist/sync/executors.js +14 -14
  16. package/dist/sync/models.js +1 -1
  17. package/dist/sync/registry.js +1 -1
  18. package/dist/sync/syncSeqPlugin.js +25 -29
  19. package/dist/tests/models.d.ts +27 -11
  20. package/dist/tests/models.js +5 -3
  21. package/dist/tests/testHelper.d.ts +9 -3
  22. package/package.json +5 -6
  23. package/src/actions.test.ts +19 -12
  24. package/src/actions.ts +2 -2
  25. package/src/api.coverage.test.ts +7 -9
  26. package/src/api.errorPaths.test.ts +47 -1
  27. package/src/api.errors.test.ts +32 -23
  28. package/src/api.ts +22 -12
  29. package/src/auth.test.ts +251 -1
  30. package/src/auth.ts +25 -23
  31. package/src/betterAuthSetup.ts +7 -7
  32. package/src/configuration.test.ts +59 -38
  33. package/src/configurationPlugin.test.ts +72 -42
  34. package/src/configurationPlugin.ts +2 -2
  35. package/src/consentApp.test.ts +12 -12
  36. package/src/expressServer.ts +11 -5
  37. package/src/githubAuth.ts +1 -3
  38. package/src/middleware.test.ts +16 -0
  39. package/src/models/versionConfig.ts +1 -1
  40. package/src/openApiBuilder.test.ts +24 -9
  41. package/src/openApiValidator.test.ts +41 -0
  42. package/src/permissions.test.ts +35 -25
  43. package/src/plugins.test.ts +24 -0
  44. package/src/plugins.ts +29 -11
  45. package/src/populate.test.ts +25 -16
  46. package/src/realtime/realtime.test.ts +239 -0
  47. package/src/realtime/realtimeApp.ts +15 -8
  48. package/src/realtime/realtimeAppSetup.test.ts +159 -0
  49. package/src/realtime/types.ts +14 -0
  50. package/src/secretProvidersGcpClient.test.ts +66 -0
  51. package/src/sync/executors.ts +16 -14
  52. package/src/sync/models.ts +2 -1
  53. package/src/sync/registry.ts +1 -1
  54. package/src/sync/syncFrontier.test.ts +2 -2
  55. package/src/sync/syncSeqPlugin.ts +43 -51
  56. package/src/tests/models.ts +8 -6
package/CHANGELOG.md CHANGED
@@ -1,125 +1,5 @@
1
1
  # Changelog
2
2
 
3
- ## 0.29.1
3
+ The changelog for all `@terreno/*` packages lives at the repository root:
4
4
 
5
- Patch release for `@terreno/api` 0.28.0's `APIError` rework. In 0.28.0 `Error.message` became exactly
6
- `title`, so anywhere the framework re-wrapped an inner error and rebuilt the wrapper's text with
7
- `errorMessage(inner)`, the inner error's `detail`, `code`, `meta`, `fields`, and `status` were
8
- silently dropped. This release makes `modelRouter` pass those errors through instead.
9
-
10
- ### Fixed
11
-
12
- - **`modelRouter` no longer re-wraps an `APIError` raised inside your code.** Every catch that used
13
- to build a generic wrapper now re-throws an `APIError` untouched, so its `status`, `title`,
14
- `detail`, `code`, and `meta` reach the client. This covers `model.create()`, the create/update
15
- `doc.save()`, populate-after-create, `postCreate`, `postUpdate`, `postDelete`, `queryFilter`, the
16
- list query, list serialization, `doc.deleteOne()`, every `responseHandler` call, and the
17
- `preUpdate` / `doc.save()` / `postUpdate` steps of the array-operation `PATCH` helper. Previously
18
- only the `transform`, `preCreate`, `preUpdate`, and `preDelete` catches had the guard. The most
19
- common casualty was an `APIError` thrown from Mongoose document middleware (`pre("save")`,
20
- `pre("validate")`), which reached the client as `{status: 400, title: "Create error", code:
21
- "create-error"}` with the consumer's `code` and `meta` gone.
22
- - **Mongoose validation and cast errors from `modelRouter` writes now carry per-field messages
23
- again.** The `model.create()` and `doc.save()` catches run `mongooseErrorToAPIError` before falling
24
- back to a generic wrapper, so a `ValidationError` surfaces as
25
- `{status: 400, title: "Validation failed", meta: {fields: {...}}}` rather than
26
- `{title: "Create error", detail: "Validation failed: name: Path \`name\` is required."}`. These
27
- errors are also marked `disableExternalErrorTracking`, so bad client input stops paging Sentry.
28
- - **`queryFilter` wrapper details are readable.** That catch used `String(error)`, which emitted
29
- `"Error: <message>"` for an `Error` and `"[object Object]"` for a thrown non-`Error`. It now uses
30
- the same message extraction as every other catch.
31
- - **Framework-thrown errors follow the 0.28.0 contract.** `api.ts`, `plugins.ts`, `actions.ts`, and
32
- `docLoader.ts` no longer interpolate per-occurrence values into `title`; the specific text moved to
33
- `detail` (plus `meta` / `source` where it is structured), and each error carries a kebab-case
34
- `code` and, where applicable, a status subclass (`BadRequestError`, `ForbiddenError`,
35
- `NotFoundError`, `ValidationError`, `InternalServerError`). Titles are now stable strings, so
36
- Sentry groups them by logical error instead of by occurrence.
37
- - **`findOneOrNone`, `findOneOrNoneFor`, and `findExactlyOne` accept `Partial<APIErrorOptions>`** for
38
- `errorArgs` instead of the deprecated `Partial<APIErrorConstructor>`. `errorArgs` is still applied
39
- last, so every field including `status` remains overridable.
40
-
41
- ### Added
42
-
43
- - **`errorDetail(error)`** — returns `` `${title}: ${detail}` `` for an `APIError` and
44
- `errorMessage(error)` for anything else. Used for the `detail` of framework wrapper errors so a
45
- nested `APIError`'s text is never lost if one does reach a wrapper.
46
-
47
- ### Changed (behavior)
48
-
49
- - **`apiUnauthorizedMiddleware` only matches a plain `Error("Unauthorized")`.** It is registered
50
- ahead of `apiErrorMiddleware`, and because `message` is now exactly `title`, it was rewriting **any**
51
- `APIError` titled `"Unauthorized"` into a bare 401 and discarding its status, `code`, and `detail`.
52
- A `new ForbiddenError({title: "Unauthorized"})` now stays a **403** with its own body; Passport's
53
- plain `Error("Unauthorized")` still becomes a quiet 401.
54
- - **An `APIError` thrown from a hook or from Mongoose middleware now returns its own status.**
55
- Previously the wrapper's hardcoded status (usually 400, or 403 for `transform`/`preDelete`) won.
56
- If you throw a non-4xx `APIError` from `postCreate`, `postUpdate`, `postDelete`, `queryFilter`,
57
- `responseHandler`, or a `pre("save")` hook, clients now see that status instead of 400.
58
- - **Framework error titles changed** where they used to embed per-occurrence values. The old text is
59
- preserved in `detail`. Notable renames: `` `${param} is not allowed as a query param.` `` →
60
- `"Query parameter not allowed"`; `` `Invalid page: ${page}` `` → `"Invalid page"`;
61
- `` `Invalid date for query parameter ${key}` `` → `"Invalid date query parameter"`;
62
- `` `Could not find ${field}/${itemId}` `` → `"Array item not found"`;
63
- `` `Could not find document to PATCH: ${id}` `` → `"Document not found"`;
64
- `` `Malformed body, array operations…` `` → `"Malformed array operation body"`;
65
- `` `Invalid array operation: ${op}` `` → `"Invalid array operation"`;
66
- `` `Patch not allowed for user…` `` → `"Update not allowed"`;
67
- `` `Access to ${method} on ${model}…denied` `` → `"Access denied"` (both `modelRouter` array
68
- operations and `runActionPermissions`); and the `plugins.ts` query statics now use
69
- `"findExactlyOne query returned no documents"`, `"findExactlyOne query returned multiple
70
- documents"`, `"findOne query returned multiple documents"`, and `"upsert find query returned
71
- multiple documents"` with the model name in `detail`/`meta`. Clients that string-match on `title`
72
- should match on `code` instead.
73
- - **A Mongoose validation failure on an array-operation `PATCH` returns `"Validation failed"`** with
74
- `meta.fields` rather than `"PATCH Pre Update error"`.
75
-
76
- ### Unchanged
77
-
78
- No HTTP statuses were changed. The 405 that `runActionPermissions` returns when a pre-document
79
- permission check fails is kept as-is: `modelRouter`'s array operations return 405 for the same check,
80
- so it is an existing (if odd) convention rather than a typo to fix in a patch release.
81
-
82
- ## 0.20.0
83
-
84
- ### Changed (breaking)
85
-
86
- - **`ConfigurationApp` `POST {basePath}/list-secrets` no longer persists secret values.** Previously it resolved secrets from the provider and wrote the resolved plaintext values into the configuration document. It is now a **read-only validation/status** endpoint: it reports, per secret field, only non-sensitive metadata (`path`, `secretName`, `version`, and a boolean `resolvable`/`isConfigured`) and never writes to the document or returns secret values. A `POST {basePath}/validate-secrets` alias with the same behavior is also registered.
87
- - **`ConfigurationApp` `PATCH {basePath}` strips `secret: true` fields** from the incoming body, so a secret value can never be written through the update path. Secret fields are read-only via this surface.
88
- - **`configurationPlugin` no longer adds the `_singleton` unique index by default.** It is now opt-in via `enforceSingletonIndex: true` so it does not double-enforce or conflict with consumers that already guarantee a single non-deleted document via the pre-save guard or their own soft-delete plugin/indexes.
89
- - **`configurationPlugin` singleton semantics are now soft-delete aware.** `getConfig`, `updateConfig`, and the pre-save guard operate on `{deleted: false}` when the schema has a `deleted` path (e.g. via `isDeletedPlugin`). A soft-deleted document no longer blocks creating a new singleton; hard deletes (`deleteOne`/`deleteMany`/`findOneAndDelete`) remain blocked.
90
- - **`configurationPlugin.updateConfig` now applies updates via `findOneAndUpdate({$set})` with dotted paths** instead of `Object.assign` + `doc.save()`. This preserves sibling fields inside nested subdocuments on partial patches and tolerates legacy/out-of-schema fields already persisted under `strict: "throw"`.
91
-
92
- ### Added
93
-
94
- - **`SecretProvider.getSecret(secretName, version?)`** — optional `version` parameter. `GcpSecretProvider` resolves `projects/{projectId}/secrets/{name}/versions/{version}` (default `latest`, full resource paths still honored); `EnvSecretProvider` ignores it. Secret fields can declare a `secretVersion` schema option, surfaced on `SecretFieldMeta.version` and passed through `resolveSecrets`.
95
- - **`CompositeSecretProvider`** — composes an ordered list of providers and returns the first non-null result; a failing provider is warn-logged (secret name only) and resolution falls through to the next.
96
- - **`CachingSecretProvider`** — wraps any provider with an in-memory TTL cache keyed by `secretName@version`, with `clear()` / `clearKey()` for rotation and tests. Caches `null` results. Never logs values.
97
- - **`ConfigurationApp` pluggable permissions** — `permissions: {read?, update?, meta?, listSecrets?}` accepts terreno permission functions (e.g. `[IsStaff]`), AND-combined like `modelRouter`. Defaults to admin-only for every route.
98
- - **`ConfigurationApp` lifecycle hooks** — `preUpdate(body, req)` (validate/normalize) and `postUpdate(config, prevValue, req)` (audit logging). Both payloads have secret values redacted.
99
- - **`flattenToDotPaths`** — exported helper used by `updateConfig`.
100
-
101
- ### Migration
102
-
103
- - If you relied on `list-secrets` to populate secret values into the configuration document, stop. Resolve secrets on-demand at runtime via `Model.resolveSecrets(provider)` (returns an in-memory `Map`) and read them from memory; never persist them.
104
- - If you depended on the `_singleton` unique index, pass `configurationPlugin(schema, {enforceSingletonIndex: true})`.
105
- - For GCP-with-env-fallback and caching, compose `new CachingSecretProvider(new CompositeSecretProvider([gcp, env]), {ttlMs})`.
106
-
107
- ## 0.16.0
108
-
109
- ### Added
110
-
111
- - **modelRouter actions** — Declare `instanceActions` and `collectionActions` on `ModelRouterOptions` for named operations at `/resource/:id/action` and `/resource/action`. Handlers receive `{req, res, user, doc?, body, query}`; return values are wrapped in `{data: ...}`. OpenAPI operations are emitted automatically when `openApi` is configured.
112
- - **`loadDocOr404`** — Shared document loader used by permission middleware and instance actions (soft-delete-aware 404 metadata preserved).
113
-
114
- ### Changed
115
-
116
- - Permission middleware doc loading now delegates to `loadDocOr404` (behavior-preserving).
117
-
118
- ### Dependencies
119
-
120
- - Added `@asteasolutions/zod-to-openapi` ^8.5.0 (direct dependency).
121
- - Added **`zod` ^4.3.6 as a peer dependency** — backends that define action Zod schemas must install `zod`.
122
-
123
- ### Migration
124
-
125
- - Regenerate frontend SDKs after adding actions; `operationId` values follow `{tag}_{actionName}` (e.g. `todos_markComplete`).
5
+ [../CHANGELOG.md](../CHANGELOG.md)
package/LICENSE CHANGED
@@ -1,202 +1,21 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship, whether in Source or
36
- Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work
38
- (an example is provided in the Appendix below).
39
-
40
- "Derivative Works" shall mean any work, whether in Source or Object
41
- form, that is based on (or derived from) the Work and for which the
42
- editorial revisions, annotations, elaborations, or other modifications
43
- represent, as a whole, an original work of authorship. For the purposes
44
- of this License, Derivative Works shall not include works that remain
45
- separable from, or merely link (or bind by name) to the interfaces of,
46
- the Work and Derivative Works thereof.
47
-
48
- "Contribution" shall mean any work of authorship, including
49
- the original version of the Work and any modifications or additions
50
- to that Work or Derivative Works thereof, that is intentionally
51
- submitted to Licensor for inclusion in the Work by the copyright owner
52
- or by an individual or Legal Entity authorized to submit on behalf of
53
- the copyright owner. For the purposes of this definition, "submitted"
54
- means any form of electronic, verbal, or written communication sent
55
- to the Licensor or its representatives, including but not limited to
56
- communication on electronic mailing lists, source code control systems,
57
- and issue tracking systems that are managed by, or on behalf of, the
58
- Licensor for the purpose of discussing and improving the Work, but
59
- excluding communication that is conspicuously marked or otherwise
60
- designated in writing by the copyright owner as "Not a Contribution."
61
-
62
- "Contributor" shall mean Licensor and any individual or Legal Entity
63
- on behalf of whom a Contribution has been received by Licensor and
64
- subsequently incorporated within the Work.
65
-
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
67
- this License, each Contributor hereby grants to You a perpetual,
68
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
- copyright license to reproduce, prepare Derivative Works of,
70
- publicly display, publicly perform, sublicense, and distribute the
71
- Work and such Derivative Works in Source or Object form.
72
-
73
- 3. Grant of Patent License. Subject to the terms and conditions of
74
- this License, each Contributor hereby grants to You a perpetual,
75
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
- (except as stated in this section) patent license to make, have made,
77
- use, offer to sell, sell, import, and otherwise transfer the Work,
78
- where such license applies only to those patent claims licensable
79
- by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by combination of their Contribution(s)
81
- with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a
83
- cross-claim or counterclaim in a lawsuit) alleging that the Work
84
- or a Contribution incorporated within the Work constitutes direct
85
- or contributory patent infringement, then any patent licenses
86
- granted to You under this License for that Work shall terminate
87
- as of the date such litigation is filed.
88
-
89
- 4. Redistribution. You may reproduce and distribute copies of the
90
- Work or Derivative Works thereof in any medium, with or without
91
- modifications, and in Source or Object form, provided that You
92
- meet the following conditions:
93
-
94
- (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
96
-
97
- (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
99
-
100
- (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
105
-
106
- (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
122
-
123
- You may add Your own copyright statement to Your modifications and
124
- may provide additional or different license terms and conditions
125
- for use, reproduction, or distribution of Your modifications, or
126
- for any such Derivative Works as a whole, provided Your use,
127
- reproduction, and distribution of the Work otherwise complies with
128
- the conditions stated in this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work
132
- by You to the Licensor shall be under the terms and conditions of
133
- this License, without any additional terms or conditions.
134
- Notwithstanding the above, nothing herein shall supersede or modify
135
- the terms of any separate license agreement you may have executed
136
- with Licensor regarding such Contributions.
137
-
138
- 6. Trademarks. This License does not grant permission to use the trade
139
- names, trademarks, service marks, or product names of the Licensor,
140
- except as required for reasonable and customary use in describing the
141
- origin of the Work and reproducing the content of the NOTICE file.
142
-
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
144
- agreed to in writing, Licensor provides the Work (and each
145
- Contributor provides its Contributions) on an "AS IS" BASIS,
146
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
- implied, including, without limitation, any warranties or conditions
148
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
- PARTICULAR PURPOSE. You are solely responsible for determining the
150
- appropriateness of using or redistributing the Work and assume any
151
- risks associated with Your exercise of permissions under this License.
152
-
153
- 8. Limitation of Liability. In no event and under no legal theory,
154
- whether in tort (including negligence), contract, or otherwise,
155
- unless required by applicable law (such as deliberate and grossly
156
- negligent acts) or agreed to in writing, shall any Contributor be
157
- liable to You for damages, including any direct, indirect, special,
158
- incidental, or consequential damages of any character arising as a
159
- result of this License or out of the use or inability to use the
160
- Work (including but not limited to damages for loss of goodwill,
161
- work stoppage, computer failure or malfunction, or any and all
162
- other commercial damages or losses), even if such Contributor
163
- has been advised of the possibility of such damages.
164
-
165
- 9. Accepting Warranty or Additional Liability. While redistributing
166
- the Work or Derivative Works thereof, You may choose to offer,
167
- and charge a fee for, acceptance of support, warranty, indemnity,
168
- or other liability obligations and/or rights consistent with this
169
- License. However, in accepting such obligations, You may act only
170
- on Your own behalf and on Your sole responsibility, not on behalf
171
- of any other Contributor, and only if You agree to indemnify,
172
- defend, and hold each Contributor harmless for any liability
173
- incurred by, or claims asserted against, such Contributor by reason
174
- of your accepting any such warranty or additional liability.
175
-
176
- END OF TERMS AND CONDITIONS
177
-
178
- APPENDIX: How to apply the Apache License to your work.
179
-
180
- To apply the Apache License to your work, attach the following
181
- boilerplate notice, with the fields enclosed by brackets "[]"
182
- replaced with your own identifying information. (Don't include
183
- the brackets!) The text should be enclosed in the appropriate
184
- comment syntax for the file format. We also recommend that a
185
- file or class name and description of purpose be included on the
186
- same "printed page" as the copyright notice for easier
187
- identification within third-party archives.
188
-
189
- Copyright 2020 Josh Gachnang
190
- Copyright 2022 Flourish Health Inc.
191
-
192
- Licensed under the Apache License, Version 2.0 (the "License");
193
- you may not use this file except in compliance with the License.
194
- You may obtain a copy of the License at
195
-
196
- http://www.apache.org/licenses/LICENSE-2.0
197
-
198
- Unless required by applicable law or agreed to in writing, software
199
- distributed under the License is distributed on an "AS IS" BASIS,
200
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
- See the License for the specific language governing permissions and
202
- limitations under the License.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Flourish Health, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/api.d.ts CHANGED
@@ -8,6 +8,7 @@ import type { PopulatePath } from "./populate";
8
8
  import type { RealtimeConfig } from "./realtime/types";
9
9
  import type { SyncConfig } from "./sync/types";
10
10
  import { type TerrenoTransformer } from "./transformers";
11
+ type ModelLike<T> = Model<T, any, any, any, any, any>;
11
12
  export type JSONPrimitive = string | number | boolean | null;
12
13
  export interface JSONArray extends Array<JSONValue> {
13
14
  }
@@ -293,8 +294,8 @@ export interface ModelRouterRegistration {
293
294
  * const todoRouter = modelRouter("/todos", Todo, options);
294
295
  * app.register(todoRouter);
295
296
  */
296
- export declare function modelRouter<T>(path: string, model: Model<T>, options: ModelRouterOptions<T>): ModelRouterRegistration;
297
- export declare function modelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>): express.Router;
297
+ export declare function modelRouter<T>(path: string, model: ModelLike<T>, options: ModelRouterOptions<T>): ModelRouterRegistration;
298
+ export declare function modelRouter<T>(model: ModelLike<T>, options: ModelRouterOptions<T>): express.Router;
298
299
  /**
299
300
  * Options for the asyncHandler function.
300
301
  */
package/dist/auth.js CHANGED
@@ -256,6 +256,17 @@ var setPasswordForUser = function (user_1, password_1) {
256
256
  });
257
257
  };
258
258
  exports.setPasswordForUser = setPasswordForUser;
259
+ /**
260
+ * Returns the duration when `ms` can parse it, otherwise logs and returns undefined so the caller
261
+ * keeps its default. Signing a token with an unparseable duration throws instead.
262
+ */
263
+ var validateDuration = function (envName, value) {
264
+ if ((0, ms_1.default)(value) === undefined) {
265
+ logger_1.logger.error("".concat(envName, " is not a valid duration: \"").concat(value, "\". Using the default instead."));
266
+ return undefined;
267
+ }
268
+ return value;
269
+ };
259
270
  /**
260
271
  * Generates both an access token (JWT) and a refresh token for a given user.
261
272
  *
@@ -279,7 +290,7 @@ var generateTokens = function (user_1, authOptions_1) {
279
290
  args_1[_i - 2] = arguments[_i];
280
291
  }
281
292
  return __awaiter(void 0, __spreadArray([user_1, authOptions_1], __read(args_1), false), void 0, function (user, authOptions, options) {
282
- var tokenSecretOrKey, tokenUser, sessionId, payload, tokenOptions, token, refreshTokenSecretOrKey, refreshToken, refreshTokenOptions;
293
+ var tokenSecretOrKey, tokenUser, sessionId, payload, tokenOptions, expiresIn, token, refreshTokenSecretOrKey, refreshToken, refreshTokenOptions, expiresIn;
283
294
  var _a;
284
295
  if (options === void 0) { options = {}; }
285
296
  return __generator(this, function (_b) {
@@ -304,15 +315,9 @@ var generateTokens = function (user_1, authOptions_1) {
304
315
  tokenOptions.expiresIn = authOptions.generateTokenExpiration(user);
305
316
  }
306
317
  else if (process.env.TOKEN_EXPIRES_IN) {
307
- try {
308
- // this call to ms is purely for validation of the env variable. If it is invalid,
309
- // we want to be able to log the error and use the default.
310
- (0, ms_1.default)(process.env.TOKEN_EXPIRES_IN);
311
- tokenOptions.expiresIn = process.env.TOKEN_EXPIRES_IN;
312
- }
313
- catch (error) {
314
- // This error will result in using the default value above of 15m.
315
- logger_1.logger.error(error);
318
+ expiresIn = validateDuration("TOKEN_EXPIRES_IN", process.env.TOKEN_EXPIRES_IN);
319
+ if (expiresIn) {
320
+ tokenOptions.expiresIn = expiresIn;
316
321
  }
317
322
  }
318
323
  if (process.env.TOKEN_ISSUER) {
@@ -328,15 +333,9 @@ var generateTokens = function (user_1, authOptions_1) {
328
333
  refreshTokenOptions.expiresIn = authOptions.generateRefreshTokenExpiration(user);
329
334
  }
330
335
  else if (process.env.REFRESH_TOKEN_EXPIRES_IN) {
331
- try {
332
- // this call to ms is purely for validation of the env variable. If it is invalid,
333
- // we want to be able to log the error and use the default.
334
- (0, ms_1.default)(process.env.REFRESH_TOKEN_EXPIRES_IN);
335
- refreshTokenOptions.expiresIn = process.env.REFRESH_TOKEN_EXPIRES_IN;
336
- }
337
- catch (error) {
338
- // This error will result in using the default value above of 30d.
339
- logger_1.logger.error(error);
336
+ expiresIn = validateDuration("REFRESH_TOKEN_EXPIRES_IN", process.env.REFRESH_TOKEN_EXPIRES_IN);
337
+ if (expiresIn) {
338
+ refreshTokenOptions.expiresIn = expiresIn;
340
339
  }
341
340
  }
342
341
  refreshToken = jsonwebtoken_1.default.sign(payload, refreshTokenSecretOrKey, refreshTokenOptions);
@@ -350,6 +349,9 @@ var generateTokens = function (user_1, authOptions_1) {
350
349
  };
351
350
  exports.generateTokens = generateTokens;
352
351
  var setupAuth = function (app, userModel) {
352
+ if (!userModel.createStrategy) {
353
+ throw new errors_1.APIError({ status: 500, title: "setupAuth userModel must have .createStrategy()" });
354
+ }
353
355
  passport_1.default.use(new passport_anonymous_1.Strategy());
354
356
  passport_1.default.use(userModel.createStrategy());
355
357
  passport_1.default.use("signup", new passport_local_1.Strategy({
@@ -375,9 +377,6 @@ var setupAuth = function (app, userModel) {
375
377
  }
376
378
  });
377
379
  }); }));
378
- if (!userModel.createStrategy) {
379
- throw new errors_1.APIError({ status: 500, title: "setupAuth userModel must have .createStrategy()" });
380
- }
381
380
  var customTokenExtractor = function (req) {
382
381
  var _a, _b, _c;
383
382
  var token = null;
@@ -394,9 +393,6 @@ var setupAuth = function (app, userModel) {
394
393
  logger_1.logger.debug("Setting up JWT Authentication");
395
394
  }
396
395
  var secretOrKey = process.env.TOKEN_SECRET;
397
- if (!secretOrKey) {
398
- throw new errors_1.APIError({ status: 500, title: "TOKEN_SECRET must be set in env." });
399
- }
400
396
  var jwtOpts = {
401
397
  issuer: process.env.TOKEN_ISSUER,
402
398
  jwtFromRequest: customTokenExtractor,
@@ -32,7 +32,20 @@ export declare const createBetterAuth: (options: CreateBetterAuthOptions) => Bet
32
32
  * and populates req.user with the application User model.
33
33
  */
34
34
  export declare const createBetterAuthSessionMiddleware: (auth: BetterAuthInstance, userModel?: UserModel) => (req: Request, _res: Response, next: NextFunction) => Promise<void>;
35
- export declare const syncBetterAuthUser: (userModel: UserModel, betterAuthUser: BetterAuthUser, oauthProvider?: string) => Promise<any>;
35
+ /**
36
+ * Syncs a Better Auth user to the application User model.
37
+ * Creates or updates the user as needed.
38
+ */
39
+ interface MutableUserDoc {
40
+ admin?: boolean;
41
+ email?: string;
42
+ name?: string;
43
+ betterAuthId?: string;
44
+ oauthProvider?: string | null;
45
+ id?: string;
46
+ save: () => Promise<unknown>;
47
+ }
48
+ export declare const syncBetterAuthUser: (userModel: UserModel, betterAuthUser: BetterAuthUser, oauthProvider?: string) => Promise<MutableUserDoc>;
36
49
  /**
37
50
  * Mounts Better Auth routes on the Express app.
38
51
  */
@@ -57,3 +70,4 @@ export declare const getBetterAuthSession: (req: Request) => BetterAuthSessionDa
57
70
  * Checks if the request has a valid Better Auth session.
58
71
  */
59
72
  export declare const hasBetterAuthSession: (req: Request) => boolean;
73
+ export {};
@@ -209,11 +209,8 @@ var createBetterAuthSessionMiddleware = function (auth, userModel) {
209
209
  }); };
210
210
  };
211
211
  exports.createBetterAuthSessionMiddleware = createBetterAuthSessionMiddleware;
212
- var syncBetterAuthUser = function (userModel, betterAuthUser, oauthProvider
213
- // noExplicitAny: return is a consumer-defined user document; tests inspect varied fields
214
- // biome-ignore lint/suspicious/noExplicitAny: return is a consumer-defined user document; tests inspect varied fields
215
- ) { return __awaiter(void 0, void 0, void 0, function () {
216
- var existingUser, userByEmail, useAsId, newUser, error_2;
212
+ var syncBetterAuthUser = function (userModel, betterAuthUser, oauthProvider) { return __awaiter(void 0, void 0, void 0, function () {
213
+ var existingUser, userByEmail, useAsId, UserDocumentConstructor, newUser, error_2;
217
214
  return __generator(this, function (_a) {
218
215
  switch (_a.label) {
219
216
  case 0:
@@ -250,7 +247,8 @@ var syncBetterAuthUser = function (userModel, betterAuthUser, oauthProvider
250
247
  return [2 /*return*/, userByEmail];
251
248
  case 6:
252
249
  useAsId = mongoose_1.default.isValidObjectId(betterAuthUser.id) ? { _id: betterAuthUser.id } : {};
253
- newUser = new userModel(__assign(__assign({}, useAsId), { admin: false, betterAuthId: betterAuthUser.id, email: betterAuthUser.email, name: betterAuthUser.name || betterAuthUser.email.split("@")[0], oauthProvider: oauthProvider || null }));
250
+ UserDocumentConstructor = userModel;
251
+ newUser = new UserDocumentConstructor(__assign(__assign({}, useAsId), { admin: false, betterAuthId: betterAuthUser.id, email: betterAuthUser.email, name: betterAuthUser.name || betterAuthUser.email.split("@")[0], oauthProvider: oauthProvider || null }));
254
252
  return [4 /*yield*/, newUser.save()];
255
253
  case 7:
256
254
  _a.sent();
@@ -314,7 +314,7 @@ var configurationPlugin = function (schema, options) {
314
314
  if (Object.keys(setFields).length === 0) {
315
315
  return [2 /*return*/, this.getConfig()];
316
316
  }
317
- return [4 /*yield*/, this.findOneAndUpdate(singletonFilter, { $set: setFields }, { new: true, runValidators: true })];
317
+ return [4 /*yield*/, this.findOneAndUpdate(singletonFilter, { $set: setFields }, { returnDocument: "after", runValidators: true })];
318
318
  case 1:
319
319
  updated = _e.sent();
320
320
  if (updated) {
@@ -327,7 +327,7 @@ var configurationPlugin = function (schema, options) {
327
327
  // No singleton yet — create one (with subdocument defaults applied), then
328
328
  // apply the patch.
329
329
  _e.sent();
330
- return [2 /*return*/, this.findOneAndUpdate(singletonFilter, { $set: setFields }, { new: true, runValidators: true }).orFail()];
330
+ return [2 /*return*/, this.findOneAndUpdate(singletonFilter, { $set: setFields }, { returnDocument: "after", runValidators: true }).orFail()];
331
331
  }
332
332
  });
333
333
  });
@@ -104,6 +104,7 @@ var express_1 = __importDefault(require("express"));
104
104
  var cloneDeep_1 = __importDefault(require("lodash/cloneDeep"));
105
105
  var on_finished_1 = __importDefault(require("on-finished"));
106
106
  var passport_1 = __importDefault(require("passport"));
107
+ var errors_1 = require("./errors");
107
108
  var logger_1 = require("./logger");
108
109
  var slackNotifier_1 = require("./notifiers/slackNotifier");
109
110
  var SLOW_READ_MAX = 200;
@@ -111,16 +112,16 @@ var SLOW_WRITE_MAX = 500;
111
112
  var IS_JEST = process.env.JEST_WORKER_ID !== undefined;
112
113
  var setupEnvironment = function () {
113
114
  if (!process.env.TOKEN_ISSUER) {
114
- throw new Error("TOKEN_ISSUER must be set in env.");
115
+ throw new errors_1.APIError({ status: 500, title: "TOKEN_ISSUER must be set in env." });
115
116
  }
116
117
  if (!process.env.TOKEN_SECRET) {
117
- throw new Error("TOKEN_SECRET must be set.");
118
+ throw new errors_1.APIError({ status: 500, title: "TOKEN_SECRET must be set." });
118
119
  }
119
120
  if (!process.env.REFRESH_TOKEN_SECRET) {
120
- throw new Error("REFRESH_TOKEN_SECRET must be set.");
121
+ throw new errors_1.APIError({ status: 500, title: "REFRESH_TOKEN_SECRET must be set." });
121
122
  }
122
123
  if (!process.env.SESSION_SECRET) {
123
- throw new Error("SESSION_SECRET must be set.");
124
+ throw new errors_1.APIError({ status: 500, title: "SESSION_SECRET must be set." });
124
125
  }
125
126
  if (!process.env.TOKEN_EXPIRES_IN && !IS_JEST) {
126
127
  logger_1.logger.warn("TOKEN_EXPIRES_IN is not set so using default.");
@@ -228,7 +229,12 @@ var cronjob = function (name, schedule, callback) {
228
229
  new cron_1.default.CronJob(cronSchedule, callback, null, true, "America/Chicago");
229
230
  }
230
231
  catch (error) {
231
- throw new Error("Failed to create cronjob: ".concat(error));
232
+ throw new errors_1.APIError({
233
+ cause: error,
234
+ detail: "Failed to create cronjob ".concat(name, " with schedule ").concat(cronSchedule, ": ").concat(error),
235
+ status: 500,
236
+ title: "Failed to create cronjob",
237
+ });
232
238
  }
233
239
  };
234
240
  exports.cronjob = cronjob;
@@ -82,10 +82,7 @@ exports.githubUserPlugin = githubUserPlugin;
82
82
  var setupGitHubAuth = function (_app, userModel, githubOptions) {
83
83
  var _a;
84
84
  var scope = (_a = githubOptions.scope) !== null && _a !== void 0 ? _a : ["user:email"];
85
- passport_1.default.use("github",
86
- // noExplicitAny: passport-github2's typed constructor overloads don't match passReqToCallback variant
87
- // biome-ignore lint/suspicious/noExplicitAny: passport-github2's typed constructor overloads don't match passReqToCallback variant
88
- new passport_github2_1.Strategy({
85
+ passport_1.default.use("github", new passport_github2_1.Strategy({
89
86
  callbackURL: githubOptions.callbackURL,
90
87
  clientID: githubOptions.clientId,
91
88
  clientSecret: githubOptions.clientSecret,
package/dist/plugins.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import mongoose, { type Document, type FilterQuery, type Schema, SchemaType, type SchemaTypeOptions } from "mongoose";
1
+ import mongoose, { type Document, type Schema, SchemaType, type SchemaTypeOptions } from "mongoose";
2
2
  import { type APIErrorOptions } from "./errors";
3
+ export type ModelQuery<T> = Partial<Record<keyof T, unknown>> & Record<string, unknown>;
3
4
  export interface BaseUser {
4
5
  admin: boolean;
5
6
  email: string;
@@ -41,7 +42,7 @@ export declare const findOneOrNone: <T>(schema: Schema<T>) => void;
41
42
  * @param query Mongoose query object
42
43
  * @param errorArgs Optional overrides for the thrown {@link APIError} when multiple match
43
44
  */
44
- export declare const findOneOrNoneFor: <T>(model: mongoose.Model<T>, query: FilterQuery<T>, errorArgs?: Partial<APIErrorOptions>) => Promise<(Document & T) | null>;
45
+ export declare const findOneOrNoneFor: <T>(model: mongoose.Model<T>, query: ModelQuery<T>, errorArgs?: Partial<APIErrorOptions>) => Promise<(Document & T) | null>;
45
46
  /**
46
47
  * This adds a static method `Model.findExactlyOne` to the schema. This or findOneOrNone should replace `Model.findOne`
47
48
  * in most instances.
@@ -67,10 +68,10 @@ export interface IsArchived {
67
68
  archived: boolean;
68
69
  }
69
70
  /**
70
- * Adds an `archived` boolean field and excludes archived documents from `find()` queries by
71
- * default. Pass `{archived: true}` explicitly to include them. This is a soft-archive analog to
72
- * {@link isDeletedPlugin}: use it when documents should be hidden from normal listings but kept
73
- * (and still directly queryable) rather than treated as deleted.
71
+ * Adds an `archived` boolean field and excludes archived documents from `find()` / `findOne()`
72
+ * queries by default. Pass `{archived: true}` explicitly to include them. This is a soft-archive
73
+ * analog to {@link isDeletedPlugin}: use it when documents should be hidden from normal listings
74
+ * but kept (and still directly queryable) rather than treated as deleted.
74
75
  * @param schema Mongoose Schema
75
76
  * @param defaultValue Default value for the `archived` field (defaults to `false`)
76
77
  */