@terreno/api 57.19.2 → 57.20.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.
Files changed (169) hide show
  1. package/CHANGELOG.md +393 -0
  2. package/dist/accountSecurity/accessActions.d.ts +38 -0
  3. package/dist/accountSecurity/accessActions.js +157 -0
  4. package/dist/accountSecurity/accountSecurityApp.d.ts +219 -0
  5. package/dist/accountSecurity/accountSecurityApp.js +438 -0
  6. package/dist/accountSecurity/accountSecurityService.d.ts +200 -0
  7. package/dist/accountSecurity/accountSecurityService.js +481 -0
  8. package/dist/accountSecurity/credentialActions.d.ts +16 -0
  9. package/dist/accountSecurity/credentialActions.js +189 -0
  10. package/dist/accountSecurity/membershipActions.d.ts +15 -0
  11. package/dist/accountSecurity/membershipActions.js +81 -0
  12. package/dist/accountSecurity/orgSecurityRoutes.d.ts +50 -0
  13. package/dist/accountSecurity/orgSecurityRoutes.js +149 -0
  14. package/dist/accountSecurity/securityEventHooks.d.ts +44 -0
  15. package/dist/accountSecurity/securityEventHooks.js +223 -0
  16. package/dist/accountSecurity/securityEvents.d.ts +162 -0
  17. package/dist/accountSecurity/securityEvents.js +114 -0
  18. package/dist/accountSecurity/securityNotifications.d.ts +125 -0
  19. package/dist/accountSecurity/securityNotifications.js +333 -0
  20. package/dist/api.js +38 -6
  21. package/dist/audit/auditEventModel.d.ts +5 -3
  22. package/dist/audit/auditEventModel.js +8 -6
  23. package/dist/audit/processQueue.js +4 -2
  24. package/dist/audit/record.d.ts +2 -2
  25. package/dist/audit/record.js +3 -0
  26. package/dist/authRecovery.js +29 -1
  27. package/dist/betterAuth.d.ts +179 -10
  28. package/dist/betterAuthApp.d.ts +15 -0
  29. package/dist/betterAuthApp.js +23 -0
  30. package/dist/betterAuthChallengeHeaders.d.ts +37 -0
  31. package/dist/betterAuthChallengeHeaders.js +180 -0
  32. package/dist/betterAuthFeatures.d.ts +54 -0
  33. package/dist/betterAuthFeatures.js +239 -0
  34. package/dist/betterAuthMethods.d.ts +73 -0
  35. package/dist/betterAuthMethods.js +55 -0
  36. package/dist/betterAuthOAuthHandoff.d.ts +10 -2
  37. package/dist/betterAuthOAuthHandoff.js +222 -24
  38. package/dist/betterAuthSetPassword.d.ts +33 -0
  39. package/dist/betterAuthSetPassword.js +166 -0
  40. package/dist/betterAuthSetup.d.ts +57 -8
  41. package/dist/betterAuthSetup.js +327 -36
  42. package/dist/consentApp.d.ts +9 -4
  43. package/dist/consentApp.js +344 -28
  44. package/dist/consentStatus.d.ts +60 -0
  45. package/dist/consentStatus.js +111 -0
  46. package/dist/errors.d.ts +6 -0
  47. package/dist/errors.js +41 -2
  48. package/dist/expressServer.js +3 -2
  49. package/dist/index.d.ts +14 -2
  50. package/dist/index.js +23 -3
  51. package/dist/mcp/oauth.js +151 -11
  52. package/dist/mcp/oauthMetadata.d.ts +2 -1
  53. package/dist/mcp/oauthMetadata.js +7 -4
  54. package/dist/models/consentResponse.js +51 -0
  55. package/dist/models/mcpOAuthClient.js +78 -2
  56. package/dist/models/mcpOAuthToken.js +28 -4
  57. package/dist/orgs/membershipGuards.d.ts +7 -0
  58. package/dist/orgs/membershipGuards.js +32 -0
  59. package/dist/orgs/orgsApp.d.ts +19 -1
  60. package/dist/orgs/orgsApp.js +55 -24
  61. package/dist/rateLimit/policies.js +8 -0
  62. package/dist/rbac/access.js +2 -1
  63. package/dist/rbac/resolve.d.ts +9 -1
  64. package/dist/rbac/resolve.js +21 -16
  65. package/dist/rbac/roleManager.d.ts +6 -0
  66. package/dist/rbac/roleManager.js +8 -7
  67. package/dist/rbac/roleModel.d.ts +1 -0
  68. package/dist/rbac/roleModel.js +45 -3
  69. package/dist/rbac/statements.d.ts +2 -2
  70. package/dist/rbac/statements.js +10 -1
  71. package/dist/rbac/types.d.ts +6 -0
  72. package/dist/rbac/userWriteGuards.js +2 -1
  73. package/dist/schemaMetadata.js +8 -1
  74. package/dist/seedRunner.js +7 -2
  75. package/dist/terrenoApp.d.ts +4 -0
  76. package/dist/terrenoApp.js +15 -0
  77. package/dist/tests/models.d.ts +5 -0
  78. package/dist/tests/models.js +8 -0
  79. package/dist/types/consentResponse.d.ts +8 -0
  80. package/dist/types/mcpOAuth.d.ts +35 -2
  81. package/package.json +6 -3
  82. package/src/__snapshots__/openApi.test.ts.snap +288 -0
  83. package/src/__snapshots__/openApiBuilder.test.ts.snap +96 -0
  84. package/src/accountSecurity/accessActions.test.ts +723 -0
  85. package/src/accountSecurity/accessActions.ts +173 -0
  86. package/src/accountSecurity/accountSecurity.test.ts +947 -0
  87. package/src/accountSecurity/accountSecurityApp.ts +720 -0
  88. package/src/accountSecurity/accountSecurityService.ts +826 -0
  89. package/src/accountSecurity/credentialActions.test.ts +867 -0
  90. package/src/accountSecurity/credentialActions.ts +260 -0
  91. package/src/accountSecurity/membershipActions.ts +89 -0
  92. package/src/accountSecurity/orgSecurityRoutes.test.ts +841 -0
  93. package/src/accountSecurity/orgSecurityRoutes.ts +232 -0
  94. package/src/accountSecurity/securityEventHooks.ts +294 -0
  95. package/src/accountSecurity/securityEvents.ts +165 -0
  96. package/src/accountSecurity/securityNotifications.test.ts +1323 -0
  97. package/src/accountSecurity/securityNotifications.ts +516 -0
  98. package/src/api.arrayOperations.test.ts +71 -0
  99. package/src/api.ts +38 -7
  100. package/src/audit/auditEventModel.ts +10 -7
  101. package/src/audit/processQueue.ts +4 -2
  102. package/src/audit/record.test.ts +15 -0
  103. package/src/audit/record.ts +10 -2
  104. package/src/authRecovery.test.ts +23 -0
  105. package/src/authRecovery.ts +34 -1
  106. package/src/authRecoveryBetterAuth.test.ts +169 -0
  107. package/src/betterAuth.ts +194 -8
  108. package/src/betterAuthApp.ts +32 -0
  109. package/src/betterAuthChallengeHeaders.test.ts +476 -0
  110. package/src/betterAuthChallengeHeaders.ts +227 -0
  111. package/src/betterAuthFeatures.test.ts +489 -0
  112. package/src/betterAuthFeatures.ts +283 -0
  113. package/src/betterAuthLinking.test.ts +844 -0
  114. package/src/betterAuthMethods.test.ts +138 -0
  115. package/src/betterAuthMethods.ts +98 -0
  116. package/src/betterAuthOAuthHandoff.test.ts +482 -69
  117. package/src/betterAuthOAuthHandoff.ts +293 -33
  118. package/src/betterAuthOAuthProxy.test.ts +421 -0
  119. package/src/betterAuthPasswordReset.test.ts +190 -0
  120. package/src/betterAuthSetPassword.test.ts +378 -0
  121. package/src/betterAuthSetPassword.ts +213 -0
  122. package/src/betterAuthSetup.test.ts +39 -7
  123. package/src/betterAuthSetup.ts +457 -38
  124. package/src/consentApp.test.ts +869 -2
  125. package/src/consentApp.ts +438 -36
  126. package/src/consentStatus.test.ts +226 -0
  127. package/src/consentStatus.ts +171 -0
  128. package/src/errors.test.ts +81 -0
  129. package/src/errors.ts +50 -1
  130. package/src/expressServer.test.ts +29 -0
  131. package/src/expressServer.ts +3 -2
  132. package/src/index.ts +30 -0
  133. package/src/mcp/oauth.test.ts +463 -2
  134. package/src/mcp/oauth.ts +184 -13
  135. package/src/mcp/oauthMetadata.ts +5 -2
  136. package/src/models/consentResponse.ts +53 -0
  137. package/src/models/mcpOAuthClient.ts +100 -3
  138. package/src/models/mcpOAuthToken.ts +30 -5
  139. package/src/orgs/membershipGuards.ts +39 -0
  140. package/src/orgs/orgRbac.test.ts +1 -1
  141. package/src/orgs/orgsApp.test.ts +101 -2
  142. package/src/orgs/orgsApp.ts +69 -28
  143. package/src/rateLimit/policies.test.ts +53 -0
  144. package/src/rateLimit/policies.ts +8 -0
  145. package/src/rbac/access.ts +4 -1
  146. package/src/rbac/resolve.test.ts +65 -0
  147. package/src/rbac/resolve.ts +37 -17
  148. package/src/rbac/roleManager.test.ts +64 -0
  149. package/src/rbac/roleManager.ts +15 -6
  150. package/src/rbac/roleModel.test.ts +174 -1
  151. package/src/rbac/roleModel.ts +66 -3
  152. package/src/rbac/routes.test.ts +58 -0
  153. package/src/rbac/statements.test.ts +4 -1
  154. package/src/rbac/statements.ts +11 -1
  155. package/src/rbac/types.ts +6 -1
  156. package/src/rbac/userWriteGuards.test.ts +48 -0
  157. package/src/rbac/userWriteGuards.ts +5 -2
  158. package/src/schemaMetadata.test.ts +39 -0
  159. package/src/schemaMetadata.ts +11 -1
  160. package/src/seedRunner.test.ts +56 -0
  161. package/src/seedRunner.ts +7 -2
  162. package/src/terrenoApp.ts +20 -0
  163. package/src/tests/accountSecurityTestApp.ts +290 -0
  164. package/src/tests/betterAuthStubs.ts +188 -0
  165. package/src/tests/mockOidcProvider.ts +105 -0
  166. package/src/tests/models.ts +13 -0
  167. package/src/tests/softwareAuthenticator.ts +183 -0
  168. package/src/types/consentResponse.ts +8 -0
  169. package/src/types/mcpOAuth.ts +39 -3
@@ -0,0 +1,105 @@
1
+ /**
2
+ * A minimal OIDC provider for Better Auth tests: discovery, an authorize step that approves at
3
+ * once, a token endpoint, and userinfo. Like a real provider it requires PKCE (S256): each
4
+ * authorize issues a fresh single-use code bound to its `code_challenge` and `redirect_uri`, and
5
+ * the token endpoint refuses a `code_verifier` or `redirect_uri` that does not match.
6
+ */
7
+ import {createHash, randomBytes} from "node:crypto";
8
+ import {once} from "node:events";
9
+ import type {Server} from "node:http";
10
+ import type {AddressInfo} from "node:net";
11
+ import express from "express";
12
+
13
+ const MOCK_ACCESS_TOKEN = "mock-access-token";
14
+
15
+ interface MockOidcUser {
16
+ email: string;
17
+ id: string;
18
+ name: string;
19
+ }
20
+
21
+ export interface MockOidcProvider {
22
+ close: () => Promise<void>;
23
+ issuer: string;
24
+ /** The user the next sign-in authenticates as. */
25
+ setUser: (user: MockOidcUser) => void;
26
+ }
27
+
28
+ interface IssuedCode {
29
+ codeChallenge: string;
30
+ redirectURI: string;
31
+ }
32
+
33
+ const s256 = (verifier: string): string =>
34
+ createHash("sha256").update(verifier).digest().toString("base64url");
35
+
36
+ export const startMockOidcProvider = async (): Promise<MockOidcProvider> => {
37
+ let issuer = "";
38
+ let user: MockOidcUser = {email: "oidc@example.com", id: "oidc-user", name: "OIDC User"};
39
+ const app = express();
40
+ app.use(express.urlencoded({extended: false}));
41
+ app.get("/.well-known/openid-configuration", (_req, res) => {
42
+ res.json({
43
+ authorization_endpoint: `${issuer}/authorize`,
44
+ issuer,
45
+ response_types_supported: ["code"],
46
+ token_endpoint: `${issuer}/token`,
47
+ userinfo_endpoint: `${issuer}/userinfo`,
48
+ });
49
+ });
50
+ const codes = new Map<string, IssuedCode>();
51
+ app.get("/authorize", (req, res) => {
52
+ const redirect = new URL(String(req.query.redirect_uri));
53
+ if (
54
+ req.query.code_challenge_method !== "S256" ||
55
+ typeof req.query.code_challenge !== "string"
56
+ ) {
57
+ redirect.searchParams.set("error", "invalid_request");
58
+ res.redirect(redirect.toString());
59
+ return;
60
+ }
61
+ const code = randomBytes(16).toString("hex");
62
+ codes.set(code, {
63
+ codeChallenge: req.query.code_challenge,
64
+ redirectURI: String(req.query.redirect_uri),
65
+ });
66
+ redirect.searchParams.set("code", code);
67
+ redirect.searchParams.set("state", String(req.query.state));
68
+ res.redirect(redirect.toString());
69
+ });
70
+ app.post("/token", (req, res) => {
71
+ const issued = codes.get(String(req.body.code));
72
+ // Codes are single use, whether or not the exchange succeeds.
73
+ codes.delete(String(req.body.code));
74
+ const isValid =
75
+ issued !== undefined &&
76
+ typeof req.body.code_verifier === "string" &&
77
+ s256(req.body.code_verifier) === issued.codeChallenge &&
78
+ req.body.redirect_uri === issued.redirectURI;
79
+ if (!isValid) {
80
+ res.status(400).json({error: "invalid_grant"});
81
+ return;
82
+ }
83
+ res.json({access_token: MOCK_ACCESS_TOKEN, expires_in: 3600, token_type: "Bearer"});
84
+ });
85
+ app.get("/userinfo", (req, res) => {
86
+ if (req.headers.authorization !== `Bearer ${MOCK_ACCESS_TOKEN}`) {
87
+ res.status(401).json({error: "invalid_token"});
88
+ return;
89
+ }
90
+ res.json({...user, email_verified: true, sub: user.id});
91
+ });
92
+ const server: Server = app.listen(0, "127.0.0.1");
93
+ await once(server, "listening");
94
+ issuer = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
95
+ return {
96
+ close: async (): Promise<void> => {
97
+ server.close();
98
+ await once(server, "close");
99
+ },
100
+ issuer,
101
+ setUser: (next: MockOidcUser): void => {
102
+ user = next;
103
+ },
104
+ };
105
+ };
@@ -31,12 +31,17 @@ export interface StaffUser extends User {
31
31
 
32
32
  export interface FoodCategory {
33
33
  _id?: string;
34
+ addendums?: FoodCategoryAddendum[];
34
35
  name: string;
35
36
  show: boolean;
36
37
  created: Date;
37
38
  updated: Date;
38
39
  }
39
40
 
41
+ interface FoodCategoryAddendum {
42
+ text: string;
43
+ }
44
+
40
45
  export interface Food {
41
46
  _id: string;
42
47
  name: string;
@@ -124,6 +129,14 @@ export const StaffUserModel = UserModel.discriminator("Staff", staffUserSchema);
124
129
 
125
130
  const foodCategorySchema = new Schema<FoodCategory>(
126
131
  {
132
+ addendums: {
133
+ description: "Extra details about this food category",
134
+ type: [
135
+ new Schema<FoodCategoryAddendum>({
136
+ text: {description: "The additional category detail", type: String},
137
+ }),
138
+ ],
139
+ },
127
140
  name: {description: "The name of the food category", type: String},
128
141
  show: {description: "Whether this category is visible", type: Boolean},
129
142
  },
@@ -0,0 +1,183 @@
1
+ /**
2
+ * A software WebAuthn authenticator for API tests: one ES256 (P-256) credential that answers
3
+ * registration with `none` attestation and signs authentication assertions, so passkey
4
+ * ceremonies run end to end against the real `@better-auth/passkey` verification.
5
+ */
6
+
7
+ import {createHash, generateKeyPairSync, type KeyObject, randomBytes, sign} from "node:crypto";
8
+
9
+ type CborValue = number | string | Buffer | CborValue[] | Map<CborValue, CborValue>;
10
+
11
+ const cborHead = (major: number, length: number): Buffer => {
12
+ if (length < 24) {
13
+ return Buffer.from([(major << 5) | length]);
14
+ }
15
+ if (length < 0x100) {
16
+ return Buffer.from([(major << 5) | 24, length]);
17
+ }
18
+ if (length < 0x10000) {
19
+ const head = Buffer.alloc(3);
20
+ head[0] = (major << 5) | 25;
21
+ head.writeUInt16BE(length, 1);
22
+ return head;
23
+ }
24
+ const head = Buffer.alloc(5);
25
+ head[0] = (major << 5) | 26;
26
+ head.writeUInt32BE(length, 1);
27
+ return head;
28
+ };
29
+
30
+ /** The subset of CBOR (RFC 8949) WebAuthn needs: ints, byte and text strings, arrays, maps. */
31
+ const encodeCbor = (value: CborValue): Buffer => {
32
+ if (typeof value === "number") {
33
+ return value >= 0 ? cborHead(0, value) : cborHead(1, -1 - value);
34
+ }
35
+ if (typeof value === "string") {
36
+ const bytes = Buffer.from(value, "utf8");
37
+ return Buffer.concat([cborHead(3, bytes.length), bytes]);
38
+ }
39
+ if (Buffer.isBuffer(value)) {
40
+ return Buffer.concat([cborHead(2, value.length), value]);
41
+ }
42
+ if (Array.isArray(value)) {
43
+ return Buffer.concat([cborHead(4, value.length), ...value.map(encodeCbor)]);
44
+ }
45
+ const entries = Array.from(value.entries());
46
+ return Buffer.concat([
47
+ cborHead(5, entries.length),
48
+ ...entries.flatMap(([key, entry]) => [encodeCbor(key), encodeCbor(entry)]),
49
+ ]);
50
+ };
51
+
52
+ const sha256 = (value: string | Buffer): Buffer => createHash("sha256").update(value).digest();
53
+
54
+ const uint32 = (value: number): Buffer => {
55
+ const bytes = Buffer.alloc(4);
56
+ bytes.writeUInt32BE(value);
57
+ return bytes;
58
+ };
59
+
60
+ // Authenticator data flags: user present, user verified, attested credential data included.
61
+ const FLAG_USER_PRESENT = 0x01;
62
+ const FLAG_USER_VERIFIED = 0x04;
63
+ const FLAG_ATTESTED_CREDENTIAL = 0x40;
64
+
65
+ /** A registration response, as `navigator.credentials.create` serialized by SimpleWebAuthn. */
66
+ interface SoftwareRegistrationResponse {
67
+ authenticatorAttachment: "platform";
68
+ clientExtensionResults: Record<string, never>;
69
+ id: string;
70
+ rawId: string;
71
+ response: {attestationObject: string; clientDataJSON: string; transports: string[]};
72
+ type: "public-key";
73
+ }
74
+
75
+ /** An authentication response, as `navigator.credentials.get` serialized by SimpleWebAuthn. */
76
+ interface SoftwareAuthenticationResponse {
77
+ authenticatorAttachment: "platform";
78
+ clientExtensionResults: Record<string, never>;
79
+ id: string;
80
+ rawId: string;
81
+ response: {authenticatorData: string; clientDataJSON: string; signature: string};
82
+ type: "public-key";
83
+ }
84
+
85
+ export interface SoftwareAuthenticator {
86
+ /** Answers `/passkey/generate-authenticate-options` with a signed assertion. */
87
+ authenticate: (options: {challenge: string}) => SoftwareAuthenticationResponse;
88
+ /** Answers `/passkey/generate-register-options` with a new credential. */
89
+ register: (options: {challenge: string}) => SoftwareRegistrationResponse;
90
+ }
91
+
92
+ /** Creates an authenticator holding one credential for `rpID`, used from `origin`. */
93
+ export const createSoftwareAuthenticator = ({
94
+ origin,
95
+ rpID,
96
+ }: {
97
+ origin: string;
98
+ rpID: string;
99
+ }): SoftwareAuthenticator => {
100
+ const {privateKey, publicKey} = generateKeyPairSync("ec", {namedCurve: "P-256"});
101
+ const credentialId = randomBytes(16);
102
+ const id = credentialId.toString("base64url");
103
+ const rpIdHash = sha256(rpID);
104
+ let signCount = 0;
105
+
106
+ const clientData = (type: string, challenge: string): Buffer =>
107
+ Buffer.from(JSON.stringify({challenge, crossOrigin: false, origin, type}));
108
+
109
+ const coseKey = (key: KeyObject): Buffer => {
110
+ const jwk = key.export({format: "jwk"});
111
+ // kty EC2, alg ES256, crv P-256, x, y.
112
+ return encodeCbor(
113
+ new Map<CborValue, CborValue>([
114
+ [1, 2],
115
+ [3, -7],
116
+ [-1, 1],
117
+ [-2, Buffer.from(jwk.x ?? "", "base64url")],
118
+ [-3, Buffer.from(jwk.y ?? "", "base64url")],
119
+ ])
120
+ );
121
+ };
122
+
123
+ return {
124
+ authenticate: ({challenge}): SoftwareAuthenticationResponse => {
125
+ signCount += 1;
126
+ const authenticatorData = Buffer.concat([
127
+ rpIdHash,
128
+ Buffer.from([FLAG_USER_PRESENT | FLAG_USER_VERIFIED]),
129
+ uint32(signCount),
130
+ ]);
131
+ const clientDataJSON = clientData("webauthn.get", challenge);
132
+ const signature = sign(
133
+ "sha256",
134
+ Buffer.concat([authenticatorData, sha256(clientDataJSON)]),
135
+ privateKey
136
+ );
137
+ return {
138
+ authenticatorAttachment: "platform",
139
+ clientExtensionResults: {},
140
+ id,
141
+ rawId: id,
142
+ response: {
143
+ authenticatorData: authenticatorData.toString("base64url"),
144
+ clientDataJSON: clientDataJSON.toString("base64url"),
145
+ signature: signature.toString("base64url"),
146
+ },
147
+ type: "public-key",
148
+ };
149
+ },
150
+ register: ({challenge}): SoftwareRegistrationResponse => {
151
+ const credentialIdLength = Buffer.alloc(2);
152
+ credentialIdLength.writeUInt16BE(credentialId.length);
153
+ const authData = Buffer.concat([
154
+ rpIdHash,
155
+ Buffer.from([FLAG_USER_PRESENT | FLAG_USER_VERIFIED | FLAG_ATTESTED_CREDENTIAL]),
156
+ uint32(signCount),
157
+ Buffer.alloc(16),
158
+ credentialIdLength,
159
+ credentialId,
160
+ coseKey(publicKey),
161
+ ]);
162
+ const attestationObject = encodeCbor(
163
+ new Map<CborValue, CborValue>([
164
+ ["fmt", "none"],
165
+ ["attStmt", new Map()],
166
+ ["authData", authData],
167
+ ])
168
+ );
169
+ return {
170
+ authenticatorAttachment: "platform",
171
+ clientExtensionResults: {},
172
+ id,
173
+ rawId: id,
174
+ response: {
175
+ attestationObject: attestationObject.toString("base64url"),
176
+ clientDataJSON: clientData("webauthn.create", challenge).toString("base64url"),
177
+ transports: ["internal"],
178
+ },
179
+ type: "public-key",
180
+ };
181
+ },
182
+ };
183
+ };
@@ -26,6 +26,14 @@ export interface ConsentResponseDocument extends mongoose.Document {
26
26
  userAgent?: string;
27
27
  contentSnapshot?: string;
28
28
  formVersionSnapshot?: number;
29
+ provisional: boolean;
30
+ provisionalSignedBy?: mongoose.Types.ObjectId;
31
+ provisionalNote?: string;
32
+ provisionalSignerIp?: string;
33
+ provisionalSignerUserAgent?: string;
34
+ voidedAt?: Date;
35
+ voidedBy?: mongoose.Types.ObjectId;
36
+ voidReason?: string;
29
37
  created: Date;
30
38
  updated: Date;
31
39
  deleted: boolean;
@@ -1,22 +1,49 @@
1
1
  import type mongoose from "mongoose";
2
2
  import type {FindExactlyOnePlugin, FindOneOrNonePlugin} from "../plugins";
3
3
 
4
- /** A client registered through dynamic client registration (RFC 7591). Public clients only. */
4
+ export type McpOAuthTokenEndpointAuthMethod = "none" | "client_secret_basic" | "client_secret_post";
5
+
6
+ /** Options for `McpOAuthClient.issueConfidential`. The secret is returned once. */
7
+ export interface McpOAuthConfidentialClientOptions {
8
+ clientId?: string;
9
+ clientName: string;
10
+ scope?: string;
11
+ tokenEndpointAuthMethod: Exclude<McpOAuthTokenEndpointAuthMethod, "none">;
12
+ userId: mongoose.Types.ObjectId | string;
13
+ }
14
+
15
+ /**
16
+ * A public authorization-code client, or a confidential `client_credentials` client bound to a
17
+ * user. Public clients leave `tokenEndpointAuthMethod` unset.
18
+ */
5
19
  export interface McpOAuthClientDocument extends mongoose.Document {
6
20
  _id: mongoose.Types.ObjectId;
7
21
  clientId: string;
8
22
  clientName?: string;
23
+ /** SHA-256 hash of the client secret. Set only for confidential clients. */
24
+ clientSecretHash?: string;
9
25
  created: Date;
10
26
  grantTypes: string[];
11
27
  redirectUris: string[];
12
28
  responseTypes: string[];
29
+ revokedAt?: Date;
13
30
  scope?: string;
31
+ tokenEndpointAuthMethod?: McpOAuthTokenEndpointAuthMethod;
14
32
  updated: Date;
33
+ /** User a `client_credentials` token acts as. */
34
+ userId?: mongoose.Types.ObjectId;
15
35
  }
16
36
 
17
37
  interface McpOAuthClientStatics
18
38
  extends FindExactlyOnePlugin<McpOAuthClientDocument>,
19
- FindOneOrNonePlugin<McpOAuthClientDocument> {}
39
+ FindOneOrNonePlugin<McpOAuthClientDocument> {
40
+ issueConfidential: (
41
+ this: McpOAuthClientModel,
42
+ options: McpOAuthConfidentialClientOptions
43
+ ) => Promise<{client: McpOAuthClientDocument; clientSecret: string}>;
44
+ /** Mark the client revoked and end every token it holds. */
45
+ revoke: (this: McpOAuthClientModel, clientId: string) => Promise<McpOAuthClientDocument | null>;
46
+ }
20
47
 
21
48
  export interface McpOAuthClientModel
22
49
  extends mongoose.Model<McpOAuthClientDocument>,
@@ -83,6 +110,11 @@ export interface McpOAuthTokenDocument extends mongoose.Document {
83
110
  clientId: string;
84
111
  created: Date;
85
112
  familyId: string;
113
+ /**
114
+ * False for an access-only `client_credentials` token. The stored refresh hash is then of a
115
+ * discarded secret and must not be exchanged.
116
+ */
117
+ hasRefreshToken?: boolean;
86
118
  refreshExpiresAt: Date;
87
119
  refreshTokenHash: string;
88
120
  resource?: string;
@@ -98,6 +130,8 @@ export interface McpOAuthTokenIssueOptions {
98
130
  accessTokenTtlSeconds: number;
99
131
  clientId: string;
100
132
  familyId?: string;
133
+ /** When false, issue an access token only and do not return a refresh token. Default true. */
134
+ includeRefreshToken?: boolean;
101
135
  refreshTokenTtlSeconds: number;
102
136
  resource?: string;
103
137
  scope?: string;
@@ -115,8 +149,10 @@ interface McpOAuthTokenStatics
115
149
  ) => Promise<{
116
150
  accessToken: string;
117
151
  mcpOAuthToken: McpOAuthTokenDocument;
118
- refreshToken: string;
152
+ refreshToken?: string;
119
153
  }>;
154
+ /** Revoke every family issued to this client. */
155
+ revokeClient: (this: McpOAuthTokenModel, clientId: string) => Promise<void>;
120
156
  revokeFamily: (this: McpOAuthTokenModel, familyId: string) => Promise<void>;
121
157
  verifyAccessToken: (
122
158
  this: McpOAuthTokenModel,