@terreno/api 57.1.0 → 57.3.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/README.md +17 -7
- package/dist/actions.js +19 -7
- package/dist/adminTypes.d.ts +26 -0
- package/dist/api.d.ts +4 -0
- package/dist/api.js +12 -24
- package/dist/auth.d.ts +23 -10
- package/dist/auth.js +97 -32
- package/dist/authRecovery.d.ts +5 -0
- package/dist/authRecovery.js +350 -0
- package/dist/authTokens.d.ts +8 -0
- package/dist/authTokens.js +162 -0
- package/dist/betterAuth.d.ts +33 -0
- package/dist/betterAuthApp.d.ts +4 -0
- package/dist/betterAuthApp.js +26 -8
- package/dist/betterAuthSetup.d.ts +44 -2
- package/dist/betterAuthSetup.js +288 -18
- package/dist/collectionRegistry.d.ts +38 -0
- package/dist/collectionRegistry.js +72 -0
- package/dist/configurationApp.d.ts +11 -2
- package/dist/configurationApp.js +2 -4
- package/dist/docLoader.js +35 -6
- package/dist/expressServer.d.ts +26 -3
- package/dist/expressServer.js +79 -11
- package/dist/index.d.ts +16 -0
- package/dist/index.js +38 -2
- package/dist/mcp/auth.d.ts +1 -0
- package/dist/mcp/auth.js +47 -25
- package/dist/mcp/handlers.d.ts +1 -1
- package/dist/mcp/handlers.js +67 -233
- package/dist/mcp/query.d.ts +2 -2
- package/dist/mcp/registry.d.ts +1 -5
- package/dist/mcp/registry.js +31 -20
- package/dist/mcp/schemaGenerator.d.ts +2 -7
- package/dist/mcp/schemaGenerator.js +41 -116
- package/dist/mcp/server.d.ts +1 -0
- package/dist/mcp/server.js +1 -0
- package/dist/mcp/serviceTokens.d.ts +16 -0
- package/dist/mcp/serviceTokens.js +345 -0
- package/dist/mcp/types.d.ts +2 -2
- package/dist/models/mcpServiceToken.d.ts +3 -0
- package/dist/models/mcpServiceToken.js +208 -0
- package/dist/openApiBuilder.d.ts +5 -4
- package/dist/openApiBuilder.js +61 -8
- package/dist/openApiCompat.js +1 -1
- package/dist/openApiValidator.js +0 -2
- package/dist/plugins.d.ts +14 -1
- package/dist/plugins.js +17 -6
- package/dist/populate.d.ts +2 -2
- package/dist/populate.js +47 -42
- package/dist/rateLimit/applyTrustProxy.d.ts +3 -0
- package/dist/rateLimit/applyTrustProxy.js +17 -0
- package/dist/rateLimit/createStore.d.ts +2 -0
- package/dist/rateLimit/createStore.js +28 -0
- package/dist/rateLimit/memoryStore.d.ts +2 -0
- package/dist/rateLimit/memoryStore.js +108 -0
- package/dist/rateLimit/middleware.d.ts +11 -0
- package/dist/rateLimit/middleware.js +110 -0
- package/dist/rateLimit/mongoStore.d.ts +3 -0
- package/dist/rateLimit/mongoStore.js +122 -0
- package/dist/rateLimit/policies.d.ts +14 -0
- package/dist/rateLimit/policies.js +151 -0
- package/dist/rateLimit/redisStore.d.ts +3 -0
- package/dist/rateLimit/redisStore.js +155 -0
- package/dist/rateLimit/types.d.ts +54 -0
- package/dist/rateLimit/types.js +9 -0
- package/dist/rbac/access.js +5 -1
- package/dist/rbac/assertAllowed.d.ts +9 -0
- package/dist/rbac/assertAllowed.js +182 -0
- package/dist/rbac/modelRouterAccess.d.ts +1 -0
- package/dist/rbac/modelRouterAccess.js +8 -4
- package/dist/rbac/permissionUtils.js +3 -2
- package/dist/rbac/resolve.js +5 -4
- package/dist/rbac/routes.js +15 -6
- package/dist/rbac/statements.d.ts +10 -0
- package/dist/rbac/statements.js +13 -2
- package/dist/realtime/deprecation.d.ts +12 -0
- package/dist/realtime/deprecation.js +32 -0
- package/dist/realtime/realtimeApp.d.ts +1 -1
- package/dist/realtime/realtimeApp.js +10 -11
- package/dist/realtime/registry.d.ts +0 -31
- package/dist/realtime/registry.js +44 -31
- package/dist/realtime/socketAuth.d.ts +5 -5
- package/dist/realtime/socketAuth.js +11 -1
- package/dist/realtime/socketUser.d.ts +5 -1
- package/dist/realtime/types.d.ts +14 -4
- package/dist/schemaMetadata.d.ts +56 -0
- package/dist/schemaMetadata.js +513 -0
- package/dist/seedRunner.d.ts +88 -0
- package/dist/seedRunner.js +627 -0
- package/dist/sync/executors.d.ts +12 -2
- package/dist/sync/executors.js +8 -10
- package/dist/sync/loadHarness.js +28 -19
- package/dist/sync/models.js +26 -24
- package/dist/sync/mutationHandler.d.ts +9 -0
- package/dist/sync/mutationHandler.js +11 -6
- package/dist/sync/registrationSideEffects.d.ts +35 -0
- package/dist/sync/registrationSideEffects.js +151 -0
- package/dist/sync/registry.d.ts +2 -52
- package/dist/sync/registry.js +38 -187
- package/dist/sync/routes.js +3 -2
- package/dist/sync/scripts/compactTombstones.js +0 -2
- package/dist/sync/syncApp.d.ts +3 -3
- package/dist/sync/syncApp.js +4 -4
- package/dist/sync/syncBatch.js +3 -2
- package/dist/sync/syncSeqPlugin.d.ts +1 -1
- package/dist/sync/syncSeqPlugin.js +20 -16
- package/dist/terrenoApp.d.ts +19 -5
- package/dist/terrenoApp.js +66 -18
- package/dist/tests/models.d.ts +2 -0
- package/dist/tests/models.js +6 -0
- package/dist/types/authToken.d.ts +33 -0
- package/dist/types/authToken.js +2 -0
- package/dist/types/mcpServiceToken.d.ts +41 -0
- package/dist/types/mcpServiceToken.js +2 -0
- package/dist/webhooks/headerValue.d.ts +2 -0
- package/dist/webhooks/headerValue.js +14 -0
- package/dist/webhooks/idempotency/memoryStore.d.ts +10 -0
- package/dist/webhooks/idempotency/memoryStore.js +65 -0
- package/dist/webhooks/idempotency/mongoStore.d.ts +4 -0
- package/dist/webhooks/idempotency/mongoStore.js +150 -0
- package/dist/webhooks/idempotency/webhookReceipt.d.ts +62 -0
- package/dist/webhooks/idempotency/webhookReceipt.js +39 -0
- package/dist/webhooks/rawBody.d.ts +14 -0
- package/dist/webhooks/rawBody.js +22 -0
- package/dist/webhooks/timingSafeEqual.d.ts +4 -0
- package/dist/webhooks/timingSafeEqual.js +17 -0
- package/dist/webhooks/verifiers/hmac.d.ts +15 -0
- package/dist/webhooks/verifiers/hmac.js +49 -0
- package/dist/webhooks/verifiers/sendgrid.d.ts +10 -0
- package/dist/webhooks/verifiers/sendgrid.js +56 -0
- package/dist/webhooks/verifiers/stripe.d.ts +9 -0
- package/dist/webhooks/verifiers/stripe.js +99 -0
- package/dist/webhooks/verifiers/twilio.d.ts +9 -0
- package/dist/webhooks/verifiers/twilio.js +112 -0
- package/dist/webhooks/webhooksApp.d.ts +33 -0
- package/dist/webhooks/webhooksApp.js +195 -0
- package/package.json +5 -6
- package/src/__snapshots__/openApi.test.ts.snap +270 -0
- package/src/__snapshots__/openApiBuilder.test.ts.snap +30 -12
- package/src/__snapshots__/schemaMetadata.test.ts.snap +197 -0
- package/src/actions.ts +20 -13
- package/src/adminModelRouter.test.ts +133 -0
- package/src/adminTypes.ts +23 -0
- package/src/api.arrayOperations.test.ts +43 -31
- package/src/api.hooks.test.ts +38 -29
- package/src/api.query.test.ts +31 -31
- package/src/api.test.ts +95 -96
- package/src/api.ts +16 -27
- package/src/auth.test.ts +107 -51
- package/src/auth.ts +98 -29
- package/src/authRecovery.test.ts +281 -0
- package/src/authRecovery.ts +279 -0
- package/src/authTokens.test.ts +94 -0
- package/src/authTokens.ts +118 -0
- package/src/authVerification.test.ts +293 -0
- package/src/betterAuth.ts +24 -0
- package/src/betterAuthApp.test.ts +1 -0
- package/src/betterAuthApp.ts +27 -9
- package/src/betterAuthSetup.test.ts +568 -38
- package/src/betterAuthSetup.ts +260 -5
- package/src/collectionRegistry.test.ts +165 -0
- package/src/collectionRegistry.ts +115 -0
- package/src/configurationApp.ts +13 -7
- package/src/docLoader.test.ts +45 -1
- package/src/docLoader.ts +37 -6
- package/src/express.d.ts +1 -0
- package/src/expressServer.test.ts +130 -66
- package/src/expressServer.ts +75 -19
- package/src/githubAuth.test.ts +60 -55
- package/src/index.ts +58 -0
- package/src/mcp/auth.test.ts +47 -0
- package/src/mcp/auth.ts +32 -11
- package/src/mcp/handlers.ts +45 -172
- package/src/mcp/integration.test.ts +59 -9
- package/src/mcp/query.ts +2 -4
- package/src/mcp/registry.ts +29 -20
- package/src/mcp/schemaGenerator.test.ts +8 -0
- package/src/mcp/schemaGenerator.ts +49 -131
- package/src/mcp/server.ts +2 -0
- package/src/mcp/serviceTokens.test.ts +330 -0
- package/src/mcp/serviceTokens.ts +307 -0
- package/src/mcp/toolGenerator.test.ts +1 -1
- package/src/mcp/types.ts +2 -6
- package/src/models/mcpServiceToken.test.ts +129 -0
- package/src/models/mcpServiceToken.ts +158 -0
- package/src/openApi.test.ts +80 -64
- package/src/openApiBuilder.test.ts +95 -7
- package/src/openApiBuilder.ts +46 -9
- package/src/openApiCompat.ts +1 -1
- package/src/openApiValidator.test.ts +49 -54
- package/src/openApiValidator.ts +1 -3
- package/src/plugins.test.ts +14 -0
- package/src/plugins.ts +34 -9
- package/src/populate.test.ts +34 -0
- package/src/populate.ts +40 -29
- package/src/rateLimit/applyTrustProxy.ts +17 -0
- package/src/rateLimit/createStore.ts +25 -0
- package/src/rateLimit/memoryStore.ts +40 -0
- package/src/rateLimit/middleware.ts +79 -0
- package/src/rateLimit/mongoStore.test.ts +80 -0
- package/src/rateLimit/mongoStore.ts +76 -0
- package/src/rateLimit/policies.ts +130 -0
- package/src/rateLimit/rateLimit.test.ts +328 -0
- package/src/rateLimit/redisStore.ioredis.test.ts +29 -0
- package/src/rateLimit/redisStore.test.ts +114 -0
- package/src/rateLimit/redisStore.ts +85 -0
- package/src/rateLimit/types.ts +64 -0
- package/src/rbac/access.ts +5 -1
- package/src/rbac/assertAllowed.test.ts +325 -0
- package/src/rbac/assertAllowed.ts +157 -0
- package/src/rbac/backfillAdmins.test.ts +124 -0
- package/src/rbac/fieldViews.test.ts +89 -0
- package/src/rbac/modelRouterAccess.test.ts +126 -0
- package/src/rbac/modelRouterAccess.ts +5 -2
- package/src/rbac/permissionUtils.ts +3 -2
- package/src/rbac/realtimeAccess.test.ts +109 -1
- package/src/rbac/resolve.ts +5 -4
- package/src/rbac/roleManager.test.ts +169 -0
- package/src/rbac/routes.test.ts +233 -0
- package/src/rbac/routes.ts +16 -6
- package/src/rbac/statements.test.ts +2 -0
- package/src/rbac/statements.ts +12 -1
- package/src/realtime/deprecation.test.ts +60 -0
- package/src/realtime/deprecation.ts +32 -0
- package/src/realtime/realtime.test.ts +8 -4
- package/src/realtime/realtimeApp.ts +10 -11
- package/src/realtime/realtimeAppSetup.test.ts +32 -5
- package/src/realtime/registry.ts +48 -42
- package/src/realtime/sessionRevalidation.test.ts +57 -44
- package/src/realtime/socketAuth.test.ts +75 -23
- package/src/realtime/socketAuth.ts +17 -6
- package/src/realtime/socketUser.ts +5 -3
- package/src/realtime/types.ts +14 -4
- package/src/schemaMetadata.test.ts +405 -0
- package/src/schemaMetadata.ts +593 -0
- package/src/scrubAdminFields.test.ts +105 -0
- package/src/seedRunner.test.ts +591 -0
- package/src/seedRunner.ts +464 -0
- package/src/sync/docMatchesMutationData.test.ts +16 -0
- package/src/sync/ensureSyncIndexes.test.ts +54 -15
- package/src/sync/executors.test.ts +40 -0
- package/src/sync/executors.ts +24 -12
- package/src/sync/integration.test.ts +15 -7
- package/src/sync/loadHarness.ts +28 -19
- package/src/sync/models.ts +32 -18
- package/src/sync/mutationHandler.test.ts +16 -16
- package/src/sync/mutationHandler.ts +9 -7
- package/src/sync/registrationSideEffects.test.ts +126 -0
- package/src/sync/registrationSideEffects.ts +131 -0
- package/src/sync/registry.ts +45 -171
- package/src/sync/routes.ts +3 -2
- package/src/sync/scripts/compactTombstones.ts +0 -2
- package/src/sync/sessionRevalidationIntegration.test.ts +12 -11
- package/src/sync/sync.test.ts +25 -23
- package/src/sync/syncApp.ts +4 -4
- package/src/sync/syncBatch.ts +3 -2
- package/src/sync/syncFrontier.test.ts +17 -15
- package/src/sync/syncPhaseC.test.ts +54 -43
- package/src/sync/syncRoutes.test.ts +51 -36
- package/src/sync/syncSeqPlugin.ts +66 -44
- package/src/sync/syncSocket.test.ts +112 -81
- package/src/terrenoApp.mcpServiceTokens.test.ts +173 -0
- package/src/terrenoApp.ts +87 -15
- package/src/tests/models.ts +14 -1
- package/src/types/authToken.ts +43 -0
- package/src/types/mcpServiceToken.ts +54 -0
- package/src/webhooks/headerValue.test.ts +22 -0
- package/src/webhooks/headerValue.ts +12 -0
- package/src/webhooks/idempotency/memoryStore.ts +34 -0
- package/src/webhooks/idempotency/mongoStore.test.ts +274 -0
- package/src/webhooks/idempotency/mongoStore.ts +83 -0
- package/src/webhooks/idempotency/webhookReceipt.ts +70 -0
- package/src/webhooks/rawBody.test.ts +74 -0
- package/src/webhooks/rawBody.ts +23 -0
- package/src/webhooks/timingSafeEqual.ts +16 -0
- package/src/webhooks/verifiers/hmac.test.ts +110 -0
- package/src/webhooks/verifiers/hmac.ts +54 -0
- package/src/webhooks/verifiers/providerVerifiers.test.ts +388 -0
- package/src/webhooks/verifiers/sendgrid.ts +59 -0
- package/src/webhooks/verifiers/stripe.ts +67 -0
- package/src/webhooks/verifiers/twilio.ts +69 -0
- package/src/webhooks/webhooksApp.test.ts +221 -0
- package/src/webhooks/webhooksApp.ts +144 -0
package/src/betterAuthSetup.ts
CHANGED
|
@@ -10,10 +10,12 @@ import {mongodbAdapter} from "better-auth/adapters/mongodb";
|
|
|
10
10
|
import {toNodeHandler} from "better-auth/node";
|
|
11
11
|
import {bearer} from "better-auth/plugins";
|
|
12
12
|
import type {Application, NextFunction, Request, Response} from "express";
|
|
13
|
+
import type {Db} from "mongodb";
|
|
13
14
|
import mongoose from "mongoose";
|
|
14
|
-
import type
|
|
15
|
+
import {type HasSetPassword, setPasswordForUser, type UserModel} from "./auth";
|
|
15
16
|
import type {BetterAuthConfig, BetterAuthSessionData, BetterAuthUser} from "./betterAuth";
|
|
16
17
|
import {APIError} from "./errors";
|
|
18
|
+
import type {AuthRecoveryMail} from "./expressServer";
|
|
17
19
|
import {logger} from "./logger";
|
|
18
20
|
import {findOneOrNoneFor} from "./plugins";
|
|
19
21
|
import {updateRequestContextFromRequest} from "./requestContext";
|
|
@@ -28,9 +30,7 @@ export type BetterAuthInstance = ReturnType<typeof betterAuth>;
|
|
|
28
30
|
*/
|
|
29
31
|
// Minimal shape we use from the MongoDB native client returned by mongoose connection
|
|
30
32
|
export interface MongoClientLike {
|
|
31
|
-
|
|
32
|
-
// biome-ignore lint/suspicious/noExplicitAny: the MongoDB driver Db type is opaque to this layer; it is passed straight to better-auth's adapter
|
|
33
|
-
db: () => any;
|
|
33
|
+
db: () => Db;
|
|
34
34
|
}
|
|
35
35
|
|
|
36
36
|
export interface CreateBetterAuthOptions {
|
|
@@ -39,6 +39,103 @@ export interface CreateBetterAuthOptions {
|
|
|
39
39
|
userModel?: UserModel;
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
+
const FALLBACK_AUTH_MAIL = {
|
|
43
|
+
resetPassword: {
|
|
44
|
+
html: '<p><a href="{{resetUrl}}">Reset your password</a></p>',
|
|
45
|
+
subject: "Reset your password",
|
|
46
|
+
text: "Reset your password using this link: {{resetUrl}}",
|
|
47
|
+
},
|
|
48
|
+
verifyEmail: {
|
|
49
|
+
html: '<p><a href="{{verifyUrl}}">Verify your email</a></p>',
|
|
50
|
+
subject: "Verify your email",
|
|
51
|
+
text: "Verify your email using this link: {{verifyUrl}}",
|
|
52
|
+
},
|
|
53
|
+
} as const;
|
|
54
|
+
|
|
55
|
+
const interpolateMail = (value: string, data: Record<string, string>): string =>
|
|
56
|
+
value.replace(/{{\s*([A-Za-z0-9_]+)\s*}}/g, (_match: string, key: string): string => {
|
|
57
|
+
return data[key] ?? "";
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
const fallbackRenderAuthMail = ({
|
|
61
|
+
publicAppUrl,
|
|
62
|
+
templateId,
|
|
63
|
+
token,
|
|
64
|
+
templates,
|
|
65
|
+
}: {
|
|
66
|
+
publicAppUrl: string;
|
|
67
|
+
templateId: "resetPassword" | "verifyEmail";
|
|
68
|
+
token: string;
|
|
69
|
+
templates?: BetterAuthConfig["authMailTemplates"];
|
|
70
|
+
}): {html?: string; subject: string; text?: string} => {
|
|
71
|
+
const template = templates?.[templateId] ?? FALLBACK_AUTH_MAIL[templateId];
|
|
72
|
+
const base = publicAppUrl.replace(/\/$/, "");
|
|
73
|
+
const resetUrl = `${base}/resetPassword?token=${encodeURIComponent(token)}`;
|
|
74
|
+
const verifyUrl = `${base}/verifyEmail?token=${encodeURIComponent(token)}`;
|
|
75
|
+
const data = {publicAppUrl: base, resetUrl, token, verifyUrl};
|
|
76
|
+
return {
|
|
77
|
+
html: template.html === undefined ? undefined : interpolateMail(template.html, data),
|
|
78
|
+
subject: interpolateMail(template.subject, data),
|
|
79
|
+
text: template.text === undefined ? undefined : interpolateMail(template.text, data),
|
|
80
|
+
};
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
export const createBetterAuthEmailHooks = (config: BetterAuthConfig) => {
|
|
84
|
+
if (!config.sendMail) {
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
87
|
+
const sendMail = config.sendMail;
|
|
88
|
+
const deliver = async (
|
|
89
|
+
templateId: "resetPassword" | "verifyEmail",
|
|
90
|
+
user: {email: string},
|
|
91
|
+
token: string
|
|
92
|
+
): Promise<void> => {
|
|
93
|
+
const publicAppUrl = config.publicAppUrl ?? "";
|
|
94
|
+
if (!publicAppUrl) {
|
|
95
|
+
logger.error("[auth] publicAppUrl is required to send Better Auth recovery mail");
|
|
96
|
+
throw new APIError({
|
|
97
|
+
status: 501,
|
|
98
|
+
title: "publicAppUrl is required to send recovery mail",
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
const rendered = (config.renderAuthMail ?? fallbackRenderAuthMail)({
|
|
102
|
+
publicAppUrl,
|
|
103
|
+
templateId,
|
|
104
|
+
templates: config.authMailTemplates,
|
|
105
|
+
token,
|
|
106
|
+
});
|
|
107
|
+
const message: AuthRecoveryMail = {
|
|
108
|
+
html: rendered.html,
|
|
109
|
+
subject: rendered.subject,
|
|
110
|
+
text: rendered.text ?? "",
|
|
111
|
+
to: user.email,
|
|
112
|
+
};
|
|
113
|
+
await sendMail(message);
|
|
114
|
+
};
|
|
115
|
+
return {
|
|
116
|
+
sendResetPassword: async ({
|
|
117
|
+
token,
|
|
118
|
+
user,
|
|
119
|
+
}: {
|
|
120
|
+
token: string;
|
|
121
|
+
url: string;
|
|
122
|
+
user: {email: string};
|
|
123
|
+
}): Promise<void> => {
|
|
124
|
+
await deliver("resetPassword", user, token);
|
|
125
|
+
},
|
|
126
|
+
sendVerificationEmail: async ({
|
|
127
|
+
token,
|
|
128
|
+
user,
|
|
129
|
+
}: {
|
|
130
|
+
token: string;
|
|
131
|
+
url: string;
|
|
132
|
+
user: {email: string};
|
|
133
|
+
}): Promise<void> => {
|
|
134
|
+
await deliver("verifyEmail", user, token);
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
};
|
|
138
|
+
|
|
42
139
|
/**
|
|
43
140
|
* Creates a Better Auth instance with MongoDB adapter.
|
|
44
141
|
*/
|
|
@@ -86,6 +183,9 @@ export const createBetterAuth = (options: CreateBetterAuthOptions): BetterAuthIn
|
|
|
86
183
|
};
|
|
87
184
|
}
|
|
88
185
|
|
|
186
|
+
const emailHooks = createBetterAuthEmailHooks(config);
|
|
187
|
+
const userModel = options.userModel;
|
|
188
|
+
|
|
89
189
|
const auth = betterAuth({
|
|
90
190
|
advanced: config.crossDomainCookies
|
|
91
191
|
? {
|
|
@@ -101,7 +201,27 @@ export const createBetterAuth = (options: CreateBetterAuthOptions): BetterAuthIn
|
|
|
101
201
|
database: mongodbAdapter(mongoClient.db()),
|
|
102
202
|
emailAndPassword: {
|
|
103
203
|
enabled: true,
|
|
204
|
+
revokeSessionsOnPasswordReset: true,
|
|
205
|
+
...(emailHooks ? {sendResetPassword: emailHooks.sendResetPassword} : {}),
|
|
206
|
+
...(userModel
|
|
207
|
+
? {
|
|
208
|
+
onPasswordReset: async (
|
|
209
|
+
{user}: {user: {email?: string; id?: string}},
|
|
210
|
+
request?: PasswordResetRequestLike
|
|
211
|
+
): Promise<void> => {
|
|
212
|
+
await applyBetterAuthPasswordResetToJwt(userModel, user, request);
|
|
213
|
+
},
|
|
214
|
+
}
|
|
215
|
+
: {}),
|
|
104
216
|
},
|
|
217
|
+
...(emailHooks
|
|
218
|
+
? {
|
|
219
|
+
emailVerification: {
|
|
220
|
+
sendOnSignUp: true,
|
|
221
|
+
sendVerificationEmail: emailHooks.sendVerificationEmail,
|
|
222
|
+
},
|
|
223
|
+
}
|
|
224
|
+
: {}),
|
|
105
225
|
// The bearer plugin lets clients authenticate with `Authorization: Bearer <sessionToken>`
|
|
106
226
|
// instead of the signed session cookie. Required for cross-origin/native clients and for
|
|
107
227
|
// websocket handshakes (RealtimeApp's Better Auth socket validator forwards the handshake
|
|
@@ -125,6 +245,141 @@ export const createBetterAuth = (options: CreateBetterAuthOptions): BetterAuthIn
|
|
|
125
245
|
return auth as unknown as BetterAuthInstance;
|
|
126
246
|
};
|
|
127
247
|
|
|
248
|
+
interface BetterAuthCredentialAccount {
|
|
249
|
+
providerId?: string;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
interface BetterAuthUserLookup {
|
|
253
|
+
user?: {id?: string};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
interface BetterAuthPasswordResetContext {
|
|
257
|
+
internalAdapter: {
|
|
258
|
+
createAccount: (account: {
|
|
259
|
+
accountId: string;
|
|
260
|
+
password: string;
|
|
261
|
+
providerId: string;
|
|
262
|
+
userId: string;
|
|
263
|
+
}) => Promise<unknown>;
|
|
264
|
+
deleteUserSessions: (userId: string) => Promise<unknown>;
|
|
265
|
+
findAccounts: (userId: string) => Promise<BetterAuthCredentialAccount[]>;
|
|
266
|
+
findUserByEmail: (email: string) => Promise<BetterAuthUserLookup | null>;
|
|
267
|
+
findUserById: (userId: string) => Promise<{id?: string} | null>;
|
|
268
|
+
updatePassword: (userId: string, password: string) => Promise<unknown>;
|
|
269
|
+
};
|
|
270
|
+
password: {hash: (password: string) => Promise<string>};
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* After JWT `POST /auth/resetPassword`, update the Better Auth credential hash
|
|
275
|
+
* (when that user exists) and delete Better Auth sessions so a dual-enrolled
|
|
276
|
+
* account cannot keep the old password or stolen sessions.
|
|
277
|
+
*/
|
|
278
|
+
export const applyJwtPasswordResetToBetterAuth = async (
|
|
279
|
+
auth: BetterAuthInstance,
|
|
280
|
+
user: {betterAuthId?: string; email?: string},
|
|
281
|
+
password: string
|
|
282
|
+
): Promise<void> => {
|
|
283
|
+
const ctx = (await auth.$context) as BetterAuthPasswordResetContext;
|
|
284
|
+
let betterAuthUserId = typeof user.betterAuthId === "string" ? user.betterAuthId : "";
|
|
285
|
+
if (!betterAuthUserId && typeof user.email === "string" && user.email.length > 0) {
|
|
286
|
+
const found = await ctx.internalAdapter.findUserByEmail(user.email);
|
|
287
|
+
betterAuthUserId = found?.user?.id ?? "";
|
|
288
|
+
}
|
|
289
|
+
if (!betterAuthUserId) {
|
|
290
|
+
const byId = user.betterAuthId
|
|
291
|
+
? await ctx.internalAdapter.findUserById(user.betterAuthId)
|
|
292
|
+
: null;
|
|
293
|
+
betterAuthUserId = byId?.id ?? "";
|
|
294
|
+
}
|
|
295
|
+
if (!betterAuthUserId) {
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
const hashedPassword = await ctx.password.hash(password);
|
|
299
|
+
const accounts = await ctx.internalAdapter.findAccounts(betterAuthUserId);
|
|
300
|
+
const hasCredential = accounts.some((account) => account.providerId === "credential");
|
|
301
|
+
if (hasCredential) {
|
|
302
|
+
await ctx.internalAdapter.updatePassword(betterAuthUserId, hashedPassword);
|
|
303
|
+
} else {
|
|
304
|
+
await ctx.internalAdapter.createAccount({
|
|
305
|
+
accountId: betterAuthUserId,
|
|
306
|
+
password: hashedPassword,
|
|
307
|
+
providerId: "credential",
|
|
308
|
+
userId: betterAuthUserId,
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
await ctx.internalAdapter.deleteUserSessions(betterAuthUserId);
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
interface PasswordResetRequestLike {
|
|
315
|
+
body?: unknown;
|
|
316
|
+
clone?: () => {json: () => Promise<unknown>};
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const passwordFromUnknown = (value: unknown): string => {
|
|
320
|
+
if (!value || typeof value !== "object") {
|
|
321
|
+
return "";
|
|
322
|
+
}
|
|
323
|
+
const record = value as Record<string, unknown>;
|
|
324
|
+
const candidate = record.newPassword ?? record.password;
|
|
325
|
+
if (typeof candidate !== "string") {
|
|
326
|
+
return "";
|
|
327
|
+
}
|
|
328
|
+
return candidate;
|
|
329
|
+
};
|
|
330
|
+
|
|
331
|
+
export const readPasswordFromBetterAuthResetRequest = async (
|
|
332
|
+
request: PasswordResetRequestLike | undefined
|
|
333
|
+
): Promise<string> => {
|
|
334
|
+
if (!request) {
|
|
335
|
+
return "";
|
|
336
|
+
}
|
|
337
|
+
const attached = passwordFromUnknown(request.body);
|
|
338
|
+
if (attached.length > 0) {
|
|
339
|
+
return attached;
|
|
340
|
+
}
|
|
341
|
+
if (typeof request.clone !== "function") {
|
|
342
|
+
return "";
|
|
343
|
+
}
|
|
344
|
+
try {
|
|
345
|
+
return passwordFromUnknown(await request.clone().json());
|
|
346
|
+
} catch {
|
|
347
|
+
return "";
|
|
348
|
+
}
|
|
349
|
+
};
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* After Better Auth password reset, update the JWT/passport hash and bump
|
|
353
|
+
* `tokenEpoch` so a dual-enrolled account cannot keep the old password or
|
|
354
|
+
* outstanding refresh tokens.
|
|
355
|
+
*/
|
|
356
|
+
export const applyBetterAuthPasswordResetToJwt = async (
|
|
357
|
+
userModel: UserModel,
|
|
358
|
+
betterAuthUser: {email?: string; id?: string},
|
|
359
|
+
request: PasswordResetRequestLike | undefined
|
|
360
|
+
): Promise<void> => {
|
|
361
|
+
const betterAuthId = typeof betterAuthUser.id === "string" ? betterAuthUser.id : "";
|
|
362
|
+
const email = typeof betterAuthUser.email === "string" ? betterAuthUser.email : "";
|
|
363
|
+
let appUser = betterAuthId ? await findOneOrNoneFor(userModel, {betterAuthId} as never) : null;
|
|
364
|
+
if (!appUser && email.length > 0) {
|
|
365
|
+
appUser = await findOneOrNoneFor(userModel, {email} as never);
|
|
366
|
+
}
|
|
367
|
+
if (!appUser) {
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
const password = await readPasswordFromBetterAuthResetRequest(request);
|
|
371
|
+
if (!password) {
|
|
372
|
+
logger.error("[auth] Better Auth password reset did not include a password to sync to JWT");
|
|
373
|
+
throw new APIError({
|
|
374
|
+
status: 500,
|
|
375
|
+
title: "Password reset could not sync to JWT credentials",
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
await setPasswordForUser(appUser as unknown as HasSetPassword, password);
|
|
379
|
+
appUser.tokenEpoch = (appUser.tokenEpoch ?? 0) + 1;
|
|
380
|
+
await appUser.save();
|
|
381
|
+
};
|
|
382
|
+
|
|
128
383
|
/**
|
|
129
384
|
* Creates Express middleware that extracts the Better Auth session
|
|
130
385
|
* and populates req.user with the application User model.
|
|
@@ -246,7 +501,7 @@ export const syncBetterAuthUser = async (
|
|
|
246
501
|
betterAuthId: betterAuthUser.id,
|
|
247
502
|
email: betterAuthUser.email,
|
|
248
503
|
name: betterAuthUser.name || betterAuthUser.email.split("@")[0],
|
|
249
|
-
oauthProvider
|
|
504
|
+
...(oauthProvider ? {oauthProvider} : {}),
|
|
250
505
|
});
|
|
251
506
|
await newUser.save();
|
|
252
507
|
logger.info(`Created new user from Better Auth: ${newUser.id}`);
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import {beforeEach, describe, expect, it} from "bun:test";
|
|
2
|
+
import {model, Schema} from "mongoose";
|
|
3
|
+
import {
|
|
4
|
+
clearCollectionRegistry,
|
|
5
|
+
getCollection,
|
|
6
|
+
listCollections,
|
|
7
|
+
registerCollection,
|
|
8
|
+
replaceCollectionOptions,
|
|
9
|
+
} from "./collectionRegistry";
|
|
10
|
+
import {clearMCPRegistry, getMCPRegistry} from "./mcp/registry";
|
|
11
|
+
import {Permissions} from "./permissions";
|
|
12
|
+
import {createdUpdatedPlugin, type IsDeleted, isDeletedPlugin} from "./plugins";
|
|
13
|
+
import {trackSyncIndexCreation} from "./sync/registrationSideEffects";
|
|
14
|
+
import {clearSyncRegistry, getSyncRegistry, registerSync} from "./sync/registry";
|
|
15
|
+
import {syncPlugin} from "./sync/syncSeqPlugin";
|
|
16
|
+
import {FoodModel} from "./tests";
|
|
17
|
+
|
|
18
|
+
interface CatalogTodo extends IsDeleted {
|
|
19
|
+
_id: string;
|
|
20
|
+
ownerId: string;
|
|
21
|
+
title: string;
|
|
22
|
+
_syncSeq?: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const catalogTodoSchema = new Schema<CatalogTodo>({
|
|
26
|
+
ownerId: {description: "The owner", type: String},
|
|
27
|
+
title: {description: "The title", required: true, type: String},
|
|
28
|
+
});
|
|
29
|
+
catalogTodoSchema.plugin(isDeletedPlugin);
|
|
30
|
+
catalogTodoSchema.plugin(createdUpdatedPlugin);
|
|
31
|
+
catalogTodoSchema.plugin(syncPlugin);
|
|
32
|
+
const CatalogTodoModel = model<CatalogTodo>("CatalogTodo", catalogTodoSchema);
|
|
33
|
+
|
|
34
|
+
const syncOptions = {
|
|
35
|
+
permissions: {
|
|
36
|
+
create: [Permissions.IsAuthenticated],
|
|
37
|
+
delete: [Permissions.IsAuthenticated],
|
|
38
|
+
list: [Permissions.IsAuthenticated],
|
|
39
|
+
read: [Permissions.IsAuthenticated],
|
|
40
|
+
update: [Permissions.IsAuthenticated],
|
|
41
|
+
},
|
|
42
|
+
sync: {scope: {type: "owner"}},
|
|
43
|
+
} as const;
|
|
44
|
+
|
|
45
|
+
const baseOptions = {
|
|
46
|
+
permissions: {
|
|
47
|
+
create: [Permissions.IsAny],
|
|
48
|
+
delete: [Permissions.IsAny],
|
|
49
|
+
list: [Permissions.IsAny],
|
|
50
|
+
read: [Permissions.IsAny],
|
|
51
|
+
update: [Permissions.IsAny],
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
describe("CollectionRegistry", () => {
|
|
56
|
+
beforeEach(() => {
|
|
57
|
+
clearCollectionRegistry();
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it("stores one catalog record per route path on registerCollection", () => {
|
|
61
|
+
registerCollection({
|
|
62
|
+
model: FoodModel,
|
|
63
|
+
options: baseOptions,
|
|
64
|
+
routePath: "/food",
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
const record = getCollection("/food");
|
|
68
|
+
expect(record?.routePath).toBe("/food");
|
|
69
|
+
expect(record?.model).toBe(FoodModel);
|
|
70
|
+
expect(record?.options).toBe(baseOptions);
|
|
71
|
+
expect(listCollections()).toHaveLength(1);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it("replaceCollectionOptions updates options for a registered path", () => {
|
|
75
|
+
registerCollection({
|
|
76
|
+
model: FoodModel,
|
|
77
|
+
options: baseOptions,
|
|
78
|
+
routePath: "/food",
|
|
79
|
+
});
|
|
80
|
+
const updatedOptions = {
|
|
81
|
+
...baseOptions,
|
|
82
|
+
permissions: {...baseOptions.permissions, list: [Permissions.IsAuthenticated]},
|
|
83
|
+
};
|
|
84
|
+
replaceCollectionOptions("/food", updatedOptions);
|
|
85
|
+
|
|
86
|
+
expect(getCollection("/food")?.options).toBe(updatedOptions);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it("replaceCollectionOptions no-ops when the route path is unknown", () => {
|
|
90
|
+
registerCollection({
|
|
91
|
+
model: FoodModel,
|
|
92
|
+
options: baseOptions,
|
|
93
|
+
routePath: "/food",
|
|
94
|
+
});
|
|
95
|
+
const originalOptions = getCollection("/food")?.options;
|
|
96
|
+
replaceCollectionOptions("/missing", {
|
|
97
|
+
permissions: {},
|
|
98
|
+
} as never);
|
|
99
|
+
|
|
100
|
+
expect(getCollection("/food")?.options).toBe(originalOptions);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it("replaceCollectionOptions updates MCP registry views with the same options object", () => {
|
|
104
|
+
clearMCPRegistry();
|
|
105
|
+
registerCollection({
|
|
106
|
+
model: FoodModel,
|
|
107
|
+
options: {...baseOptions, mcp: {methods: ["list"]}},
|
|
108
|
+
routePath: "/food",
|
|
109
|
+
});
|
|
110
|
+
const updatedOptions = {
|
|
111
|
+
...baseOptions,
|
|
112
|
+
mcp: {methods: ["read"]},
|
|
113
|
+
} as typeof baseOptions & {mcp: {methods: ["read"]}};
|
|
114
|
+
replaceCollectionOptions("/food", updatedOptions);
|
|
115
|
+
|
|
116
|
+
expect(getCollection("/food")?.options).toBe(updatedOptions);
|
|
117
|
+
expect(getMCPRegistry()[0]?.options).toBe(updatedOptions);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
it("replaceCollectionOptions updates sync registry views with the same options object", () => {
|
|
121
|
+
clearSyncRegistry();
|
|
122
|
+
registerSync({
|
|
123
|
+
config: {scope: {type: "owner"}},
|
|
124
|
+
model: CatalogTodoModel,
|
|
125
|
+
options: syncOptions,
|
|
126
|
+
routePath: "/catalogTodos",
|
|
127
|
+
});
|
|
128
|
+
const updatedOptions = {
|
|
129
|
+
...syncOptions,
|
|
130
|
+
permissions: {...syncOptions.permissions, list: [Permissions.IsAny]},
|
|
131
|
+
};
|
|
132
|
+
replaceCollectionOptions("/catalogTodos", updatedOptions);
|
|
133
|
+
|
|
134
|
+
expect(getCollection("/catalogTodos")?.options).toBe(updatedOptions);
|
|
135
|
+
expect(getSyncRegistry()[0]?.options).toBe(updatedOptions);
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it("rejects re-registering sync at the same route path", () => {
|
|
139
|
+
clearSyncRegistry();
|
|
140
|
+
registerSync({
|
|
141
|
+
config: {scope: {type: "owner"}},
|
|
142
|
+
model: CatalogTodoModel,
|
|
143
|
+
options: syncOptions,
|
|
144
|
+
routePath: "/catalogTodos",
|
|
145
|
+
});
|
|
146
|
+
expect(() =>
|
|
147
|
+
registerSync({
|
|
148
|
+
config: {scope: {type: "owner"}},
|
|
149
|
+
model: CatalogTodoModel,
|
|
150
|
+
options: syncOptions,
|
|
151
|
+
routePath: "/catalogTodos",
|
|
152
|
+
})
|
|
153
|
+
).toThrow(/already registered/);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it("clearCollectionRegistry resets deferred sync index tasks", async () => {
|
|
157
|
+
clearCollectionRegistry();
|
|
158
|
+
trackSyncIndexCreation(async () => {
|
|
159
|
+
throw new Error("should not run");
|
|
160
|
+
});
|
|
161
|
+
clearCollectionRegistry();
|
|
162
|
+
const {ensureSyncIndexes} = await import("./sync/registrationSideEffects");
|
|
163
|
+
await expect(ensureSyncIndexes()).resolves.toBeUndefined();
|
|
164
|
+
});
|
|
165
|
+
});
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Process-global catalog of modelRouter collections, keyed by routePath
|
|
3
|
+
* (e.g. `/todos`). MCP, realtime, and Sync read this Map instead of each
|
|
4
|
+
* keeping their own list. `modelRouter` is the writer; surface `register*`
|
|
5
|
+
* / `update*` / `clear*` helpers are wrappers around this module.
|
|
6
|
+
*
|
|
7
|
+
* TerrenoApp later injects `accessControl` into options. That patch goes
|
|
8
|
+
* through replaceCollectionOptions so all three surfaces see one options
|
|
9
|
+
* object. Surface flags stay sticky (OR) so a later replace cannot drop
|
|
10
|
+
* mcp/realtime/sync once enabled. First-time sync enable still runs schema
|
|
11
|
+
* and index guards in registrationSideEffects — not here — so catalog
|
|
12
|
+
* writes stay a Map update.
|
|
13
|
+
*/
|
|
14
|
+
import type {Model} from "mongoose";
|
|
15
|
+
|
|
16
|
+
import type {ModelRouterOptions} from "./api";
|
|
17
|
+
import {APIError} from "./errors";
|
|
18
|
+
import {
|
|
19
|
+
applySyncRegistrationSideEffects,
|
|
20
|
+
clearSyncIndexCreationTasks,
|
|
21
|
+
} from "./sync/registrationSideEffects";
|
|
22
|
+
|
|
23
|
+
export interface CollectionSurfaces {
|
|
24
|
+
mcp: boolean;
|
|
25
|
+
realtime: boolean;
|
|
26
|
+
sync: boolean;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface CollectionRecord {
|
|
30
|
+
model: Model<unknown>;
|
|
31
|
+
options: ModelRouterOptions<unknown>;
|
|
32
|
+
routePath: string;
|
|
33
|
+
surfaces: CollectionSurfaces;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const collectionRegistry = new Map<string, CollectionRecord>();
|
|
37
|
+
|
|
38
|
+
/** OR new option flags onto existing ones so a patch cannot disable a surface. */
|
|
39
|
+
const deriveSurfaces = (
|
|
40
|
+
options: ModelRouterOptions<unknown>,
|
|
41
|
+
existing?: CollectionSurfaces
|
|
42
|
+
): CollectionSurfaces => ({
|
|
43
|
+
mcp: Boolean(options.mcp) || (existing?.mcp ?? false),
|
|
44
|
+
realtime: Boolean(options.realtime) || (existing?.realtime ?? false),
|
|
45
|
+
sync: Boolean(options.sync) || (existing?.sync ?? false),
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
/** Insert or merge a collection. First sync enable runs schema/index guards. */
|
|
49
|
+
export const registerCollection = <T>({
|
|
50
|
+
model,
|
|
51
|
+
options,
|
|
52
|
+
routePath,
|
|
53
|
+
}: {
|
|
54
|
+
model: Model<T>;
|
|
55
|
+
options: ModelRouterOptions<T>;
|
|
56
|
+
routePath: string;
|
|
57
|
+
}): void => {
|
|
58
|
+
const existing = collectionRegistry.get(routePath);
|
|
59
|
+
const wasSyncEnabled = existing?.surfaces.sync ?? false;
|
|
60
|
+
|
|
61
|
+
if (options.sync && wasSyncEnabled) {
|
|
62
|
+
const collectionTag = routePath.replace(/^\//, "");
|
|
63
|
+
throw new APIError({
|
|
64
|
+
status: 500,
|
|
65
|
+
title:
|
|
66
|
+
`Sync collection tag "${collectionTag}" is already registered (routePath ${routePath}). ` +
|
|
67
|
+
"Each synced model must have a unique route path.",
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (options.sync && !wasSyncEnabled) {
|
|
72
|
+
applySyncRegistrationSideEffects({
|
|
73
|
+
config: options.sync,
|
|
74
|
+
existingSyncEntries: listCollections()
|
|
75
|
+
.filter((record) => record.surfaces.sync)
|
|
76
|
+
.map((record) => ({
|
|
77
|
+
collectionTag: record.routePath.replace(/^\//, ""),
|
|
78
|
+
modelName: record.model.modelName,
|
|
79
|
+
})),
|
|
80
|
+
model,
|
|
81
|
+
options,
|
|
82
|
+
routePath,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
collectionRegistry.set(routePath, {
|
|
87
|
+
model: model as unknown as Model<unknown>,
|
|
88
|
+
options: options as ModelRouterOptions<unknown>,
|
|
89
|
+
routePath,
|
|
90
|
+
surfaces: deriveSurfaces(options as ModelRouterOptions<unknown>, existing?.surfaces),
|
|
91
|
+
});
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/** Swap the options pointer after TerrenoApp enriches it. Unknown path is a no-op. */
|
|
95
|
+
export const replaceCollectionOptions = (
|
|
96
|
+
routePath: string,
|
|
97
|
+
options: ModelRouterOptions<unknown>
|
|
98
|
+
): void => {
|
|
99
|
+
const existing = collectionRegistry.get(routePath);
|
|
100
|
+
if (!existing) {
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
existing.options = options;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
export const getCollection = (routePath: string): CollectionRecord | undefined =>
|
|
107
|
+
collectionRegistry.get(routePath);
|
|
108
|
+
|
|
109
|
+
export const listCollections = (): CollectionRecord[] => Array.from(collectionRegistry.values());
|
|
110
|
+
|
|
111
|
+
/** Wipe the catalog and queued sync indexes so tests cannot leave a stale surface. */
|
|
112
|
+
export const clearCollectionRegistry = (): void => {
|
|
113
|
+
collectionRegistry.clear();
|
|
114
|
+
clearSyncIndexCreationTasks();
|
|
115
|
+
};
|
package/src/configurationApp.ts
CHANGED
|
@@ -127,14 +127,22 @@ export type ConfigurationPostUpdateHook = (
|
|
|
127
127
|
req: express.Request
|
|
128
128
|
) => void | Promise<void>;
|
|
129
129
|
|
|
130
|
+
/**
|
|
131
|
+
* The subset of a Mongoose model that ConfigurationApp inspects. Structural (rather than
|
|
132
|
+
* `Model<T>`) so consumers can pass any configuration model without generic invariance
|
|
133
|
+
* issues; the configurationPlugin statics are looked up at registration time.
|
|
134
|
+
*/
|
|
135
|
+
export interface ConfigurationModelLike {
|
|
136
|
+
modelName: string;
|
|
137
|
+
schema: Schema;
|
|
138
|
+
}
|
|
139
|
+
|
|
130
140
|
/**
|
|
131
141
|
* Options for ConfigurationApp.
|
|
132
142
|
*/
|
|
133
143
|
export interface ConfigurationAppOptions {
|
|
134
144
|
/** The Mongoose model with configurationPlugin applied. */
|
|
135
|
-
|
|
136
|
-
// biome-ignore lint/suspicious/noExplicitAny: Model<any> required for invariance — consumers pass arbitrary configuration models
|
|
137
|
-
model: Model<any>;
|
|
145
|
+
model: ConfigurationModelLike;
|
|
138
146
|
/** Base path for configuration routes. Defaults to "/configuration". */
|
|
139
147
|
basePath?: string;
|
|
140
148
|
/** Per-field widget overrides (e.g., {"ai.systemPrompt": "markdown"}). */
|
|
@@ -357,7 +365,7 @@ export class ConfigurationApp implements TerrenoPlugin {
|
|
|
357
365
|
const schema = ConfigModel.schema;
|
|
358
366
|
|
|
359
367
|
// Build metadata by inspecting the schema
|
|
360
|
-
const meta = this.buildMetadata(
|
|
368
|
+
const meta = this.buildMetadata(schema);
|
|
361
369
|
|
|
362
370
|
// GET /configuration/meta — schema metadata for the frontend
|
|
363
371
|
app.get(
|
|
@@ -479,9 +487,7 @@ export class ConfigurationApp implements TerrenoPlugin {
|
|
|
479
487
|
* Top-level fields with subschemas become sections.
|
|
480
488
|
* Top-level scalar fields go into a "General" section.
|
|
481
489
|
*/
|
|
482
|
-
|
|
483
|
-
// biome-ignore lint/suspicious/noExplicitAny: Model<any> required for invariance with consumer-supplied configuration models
|
|
484
|
-
private buildMetadata(_model: Model<any>, schema: Schema): ConfigurationMetaResponse {
|
|
490
|
+
private buildMetadata(schema: Schema): ConfigurationMetaResponse {
|
|
485
491
|
const sections: ConfigSectionMeta[] = [];
|
|
486
492
|
const generalFields: Record<string, ConfigFieldMeta> = {};
|
|
487
493
|
|
package/src/docLoader.test.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import {describe, expect, it, mock} from "bun:test";
|
|
2
|
-
import type
|
|
2
|
+
import mongoose, {type Model} from "mongoose";
|
|
3
3
|
import {loadDocOr404} from "./docLoader";
|
|
4
4
|
import {APIError} from "./errors";
|
|
5
5
|
|
|
@@ -38,6 +38,50 @@ describe("loadDocOr404", () => {
|
|
|
38
38
|
await expect(loadDocOr404(model, "507f1f77bcf86cd799439011")).rejects.toBe(original);
|
|
39
39
|
});
|
|
40
40
|
|
|
41
|
+
it("maps CastError on a populate path to a GET error, not 404", async () => {
|
|
42
|
+
const model = {
|
|
43
|
+
collection: {findOne: mock(async () => null)},
|
|
44
|
+
findById: mock(() => ({
|
|
45
|
+
exec: mock(async () => {
|
|
46
|
+
throw new mongoose.Error.CastError("ObjectId", "not-an-object-id", "ownerId");
|
|
47
|
+
}),
|
|
48
|
+
})),
|
|
49
|
+
modelName: "MockModel",
|
|
50
|
+
} as unknown as Model<unknown>;
|
|
51
|
+
|
|
52
|
+
try {
|
|
53
|
+
await loadDocOr404(model, "507f1f77bcf86cd799439011");
|
|
54
|
+
expect.unreachable("expected loadDocOr404 to throw");
|
|
55
|
+
} catch (error) {
|
|
56
|
+
expect(error).toBeInstanceOf(APIError);
|
|
57
|
+
const apiError = error as APIError;
|
|
58
|
+
expect(apiError.status).toBe(500);
|
|
59
|
+
expect(apiError.title).toBe("GET error");
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it("maps CastError from findById to a 404", async () => {
|
|
64
|
+
const model = {
|
|
65
|
+
collection: {findOne: mock(async () => null)},
|
|
66
|
+
findById: mock(() => ({
|
|
67
|
+
exec: mock(async () => {
|
|
68
|
+
throw new mongoose.Error.CastError("ObjectId", "not-an-object-id", "_id");
|
|
69
|
+
}),
|
|
70
|
+
})),
|
|
71
|
+
modelName: "MockModel",
|
|
72
|
+
} as unknown as Model<unknown>;
|
|
73
|
+
|
|
74
|
+
try {
|
|
75
|
+
await loadDocOr404(model, "not-an-object-id");
|
|
76
|
+
expect.unreachable("expected loadDocOr404 to throw");
|
|
77
|
+
} catch (error) {
|
|
78
|
+
expect(error).toBeInstanceOf(APIError);
|
|
79
|
+
const apiError = error as APIError;
|
|
80
|
+
expect(apiError.status).toBe(404);
|
|
81
|
+
expect(apiError.title).toBe("Document not found");
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
|
|
41
85
|
it("returns plain not found when document does not exist", async () => {
|
|
42
86
|
const model = {
|
|
43
87
|
collection: {findOne: mock(async () => null)},
|