@terreno/api 0.30.0 → 56.0.0-beta.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 (226) hide show
  1. package/dist/api.d.ts +10 -0
  2. package/dist/api.js +110 -361
  3. package/dist/auth.d.ts +26 -0
  4. package/dist/auth.js +100 -1
  5. package/dist/betterAuth.d.ts +5 -0
  6. package/dist/betterAuthSetup.js +23 -4
  7. package/dist/docLoader.js +12 -9
  8. package/dist/errors.d.ts +13 -0
  9. package/dist/errors.js +29 -1
  10. package/dist/index.d.ts +17 -1
  11. package/dist/index.js +29 -1
  12. package/dist/middleware.d.ts +7 -0
  13. package/dist/middleware.js +16 -1
  14. package/dist/openApiCompat.d.ts +10 -1
  15. package/dist/openApiCompat.js +115 -47
  16. package/dist/permissions.d.ts +27 -0
  17. package/dist/permissions.js +42 -1
  18. package/dist/plugins.d.ts +13 -0
  19. package/dist/plugins.js +35 -1
  20. package/dist/realtime/changeStreamWatcher.d.ts +100 -3
  21. package/dist/realtime/changeStreamWatcher.js +542 -137
  22. package/dist/realtime/realtimeApp.d.ts +2 -0
  23. package/dist/realtime/realtimeApp.js +73 -21
  24. package/dist/realtime/sessionRevalidation.d.ts +90 -0
  25. package/dist/realtime/sessionRevalidation.js +438 -0
  26. package/dist/realtime/socketAuth.d.ts +97 -0
  27. package/dist/realtime/socketAuth.js +272 -0
  28. package/dist/realtime/socketUser.d.ts +54 -0
  29. package/dist/realtime/socketUser.js +75 -5
  30. package/dist/realtime/types.d.ts +40 -0
  31. package/dist/secretProviders.d.ts +23 -0
  32. package/dist/secretProviders.js +9 -3
  33. package/dist/sync/executors.d.ts +198 -0
  34. package/dist/sync/executors.js +670 -0
  35. package/dist/sync/loadHarness.js +807 -0
  36. package/dist/sync/models.d.ts +216 -0
  37. package/dist/sync/models.js +644 -0
  38. package/dist/sync/mutationHandler.d.ts +97 -0
  39. package/dist/sync/mutationHandler.js +886 -0
  40. package/dist/sync/registry.d.ts +73 -0
  41. package/dist/sync/registry.js +223 -0
  42. package/dist/sync/routes.d.ts +62 -0
  43. package/dist/sync/routes.js +936 -0
  44. package/dist/sync/scripts/compactTombstones.d.ts +47 -0
  45. package/dist/sync/scripts/compactTombstones.js +270 -0
  46. package/dist/sync/serialize.d.ts +20 -0
  47. package/dist/{tests/bunSetup.js → sync/serialize.js} +35 -68
  48. package/dist/sync/socketHandlers.d.ts +54 -0
  49. package/dist/sync/socketHandlers.js +470 -0
  50. package/dist/sync/streams.d.ts +85 -0
  51. package/dist/sync/streams.js +221 -0
  52. package/dist/sync/syncApp.d.ts +29 -0
  53. package/dist/sync/syncApp.js +44 -0
  54. package/dist/sync/syncBatch.d.ts +71 -0
  55. package/dist/sync/syncBatch.js +252 -0
  56. package/dist/sync/syncSeqPlugin.d.ts +8 -0
  57. package/dist/sync/syncSeqPlugin.js +903 -0
  58. package/dist/sync/types.d.ts +254 -0
  59. package/dist/sync/types.js +9 -0
  60. package/dist/terrenoApp.js +90 -27
  61. package/dist/vendor/wesleytodd-openapi/index.d.ts +1 -1
  62. package/dist/vendor/wesleytodd-openapi/lib/ui.d.ts +2 -1
  63. package/package.json +7 -6
  64. package/src/__tests__/openApiCompat.test.ts +20 -0
  65. package/src/actions.openApi.test.ts +7 -10
  66. package/src/api.test.ts +12 -0
  67. package/src/api.ts +87 -295
  68. package/src/auth.test.ts +128 -176
  69. package/src/auth.ts +109 -0
  70. package/src/betterAuth.ts +6 -0
  71. package/src/betterAuthSetup.test.ts +34 -0
  72. package/src/betterAuthSetup.ts +20 -1
  73. package/src/docLoader.ts +3 -1
  74. package/src/errors.ts +33 -0
  75. package/src/expressServer.test.ts +7 -1
  76. package/src/index.ts +42 -0
  77. package/src/middleware.test.ts +40 -1
  78. package/src/middleware.ts +15 -0
  79. package/src/openApiCompat.ts +99 -45
  80. package/src/permissions.test.ts +75 -1
  81. package/src/permissions.ts +49 -0
  82. package/src/plugins.test.ts +54 -0
  83. package/src/plugins.ts +43 -0
  84. package/src/realtime/changeStreamWatcher.ts +552 -114
  85. package/src/realtime/realtime.test.ts +157 -0
  86. package/src/realtime/realtimeApp.ts +75 -11
  87. package/src/realtime/sessionRevalidation.test.ts +423 -0
  88. package/src/realtime/sessionRevalidation.ts +273 -0
  89. package/src/realtime/socketAuth.test.ts +355 -0
  90. package/src/realtime/socketAuth.ts +228 -0
  91. package/src/realtime/socketUser.ts +69 -0
  92. package/src/realtime/types.ts +40 -0
  93. package/src/secretProviders.test.ts +7 -1
  94. package/src/secretProviders.ts +15 -3
  95. package/src/sync/ensureSyncIndexes.test.ts +144 -0
  96. package/src/sync/executors.test.ts +882 -0
  97. package/src/sync/executors.ts +703 -0
  98. package/src/sync/integration.test.ts +1160 -0
  99. package/src/sync/loadHarness.ts +618 -0
  100. package/src/sync/models.ts +640 -0
  101. package/src/sync/mutationHandler.test.ts +1252 -0
  102. package/src/sync/mutationHandler.ts +850 -0
  103. package/src/sync/registry.ts +232 -0
  104. package/src/sync/routes.ts +812 -0
  105. package/src/sync/scripts/compactTombstones.test.ts +249 -0
  106. package/src/sync/scripts/compactTombstones.ts +145 -0
  107. package/src/sync/serialize.ts +48 -0
  108. package/src/sync/sessionRevalidationIntegration.test.ts +281 -0
  109. package/src/sync/socketHandlers.ts +320 -0
  110. package/src/sync/streams.ts +188 -0
  111. package/src/sync/sync.test.ts +582 -0
  112. package/src/sync/syncApp.ts +44 -0
  113. package/src/sync/syncBatch.ts +219 -0
  114. package/src/sync/syncFrontier.test.ts +494 -0
  115. package/src/sync/syncPhaseC.test.ts +718 -0
  116. package/src/sync/syncRoutes.test.ts +865 -0
  117. package/src/sync/syncSeqPlugin.ts +738 -0
  118. package/src/sync/syncSocket.test.ts +1440 -0
  119. package/src/sync/types.ts +270 -0
  120. package/src/terrenoApp.ts +37 -17
  121. package/src/tests/bunSetup.ts +8 -0
  122. package/tsconfig.json +4 -4
  123. package/tsconfig.typedoc.json +7 -1
  124. package/dist/__tests__/openApiCompat.test.js +0 -317
  125. package/dist/__tests__/versionCheckPlugin.test.d.ts +0 -1
  126. package/dist/__tests__/versionCheckPlugin.test.js +0 -597
  127. package/dist/actions.openApi.test.d.ts +0 -1
  128. package/dist/actions.openApi.test.js +0 -255
  129. package/dist/actions.test.d.ts +0 -1
  130. package/dist/actions.test.js +0 -1089
  131. package/dist/api.arrayOperations.test.d.ts +0 -1
  132. package/dist/api.arrayOperations.test.js +0 -878
  133. package/dist/api.asyncHandler.test.d.ts +0 -1
  134. package/dist/api.asyncHandler.test.js +0 -236
  135. package/dist/api.coverage.test.d.ts +0 -1
  136. package/dist/api.coverage.test.js +0 -194
  137. package/dist/api.errorPaths.test.d.ts +0 -1
  138. package/dist/api.errorPaths.test.js +0 -801
  139. package/dist/api.errors.test.d.ts +0 -1
  140. package/dist/api.errors.test.js +0 -185
  141. package/dist/api.hooks.test.d.ts +0 -1
  142. package/dist/api.hooks.test.js +0 -950
  143. package/dist/api.query.test.d.ts +0 -1
  144. package/dist/api.query.test.js +0 -948
  145. package/dist/api.test.d.ts +0 -1
  146. package/dist/api.test.js +0 -2820
  147. package/dist/auth.compile.test.d.ts +0 -1
  148. package/dist/auth.compile.test.js +0 -201
  149. package/dist/auth.coverage.test.d.ts +0 -1
  150. package/dist/auth.coverage.test.js +0 -202
  151. package/dist/auth.test.d.ts +0 -1
  152. package/dist/auth.test.js +0 -2286
  153. package/dist/betterAuth.test.d.ts +0 -1
  154. package/dist/betterAuth.test.js +0 -181
  155. package/dist/betterAuthApp.test.d.ts +0 -1
  156. package/dist/betterAuthApp.test.js +0 -242
  157. package/dist/betterAuthSetup.test.d.ts +0 -1
  158. package/dist/betterAuthSetup.test.js +0 -762
  159. package/dist/config.test.d.ts +0 -1
  160. package/dist/config.test.js +0 -353
  161. package/dist/configuration.test.d.ts +0 -1
  162. package/dist/configuration.test.js +0 -980
  163. package/dist/configurationPlugin.test.d.ts +0 -1
  164. package/dist/configurationPlugin.test.js +0 -827
  165. package/dist/consentApp.test.d.ts +0 -1
  166. package/dist/consentApp.test.js +0 -1415
  167. package/dist/docLoader.test.d.ts +0 -1
  168. package/dist/docLoader.test.js +0 -137
  169. package/dist/envConfigurationPlugin.test.d.ts +0 -1
  170. package/dist/envConfigurationPlugin.test.js +0 -369
  171. package/dist/errors.test.d.ts +0 -1
  172. package/dist/errors.test.js +0 -607
  173. package/dist/expressServer.test.d.ts +0 -1
  174. package/dist/expressServer.test.js +0 -1249
  175. package/dist/githubAuth.test.d.ts +0 -1
  176. package/dist/githubAuth.test.js +0 -1142
  177. package/dist/httpClient.test.d.ts +0 -1
  178. package/dist/httpClient.test.js +0 -1471
  179. package/dist/logger.test.d.ts +0 -1
  180. package/dist/logger.test.js +0 -685
  181. package/dist/middleware.test.d.ts +0 -1
  182. package/dist/middleware.test.js +0 -241
  183. package/dist/notifiers/googleChatNotifier.test.d.ts +0 -1
  184. package/dist/notifiers/googleChatNotifier.test.js +0 -298
  185. package/dist/notifiers/slackNotifier.test.d.ts +0 -1
  186. package/dist/notifiers/slackNotifier.test.js +0 -297
  187. package/dist/notifiers/zoomNotifier.test.d.ts +0 -1
  188. package/dist/notifiers/zoomNotifier.test.js +0 -373
  189. package/dist/openApi.test.d.ts +0 -1
  190. package/dist/openApi.test.js +0 -620
  191. package/dist/openApiBuilder.test.d.ts +0 -1
  192. package/dist/openApiBuilder.test.js +0 -601
  193. package/dist/openApiEtag.test.d.ts +0 -1
  194. package/dist/openApiEtag.test.js +0 -86
  195. package/dist/openApiValidator.test.d.ts +0 -1
  196. package/dist/openApiValidator.test.js +0 -761
  197. package/dist/permissions.middleware.test.d.ts +0 -1
  198. package/dist/permissions.middleware.test.js +0 -308
  199. package/dist/permissions.test.d.ts +0 -1
  200. package/dist/permissions.test.js +0 -439
  201. package/dist/plugins.test.d.ts +0 -1
  202. package/dist/plugins.test.js +0 -890
  203. package/dist/populate.test.d.ts +0 -1
  204. package/dist/populate.test.js +0 -373
  205. package/dist/realtime/realtime.test.d.ts +0 -10
  206. package/dist/realtime/realtime.test.js +0 -3982
  207. package/dist/requestContext.test.d.ts +0 -1
  208. package/dist/requestContext.test.js +0 -412
  209. package/dist/scriptRunner.test.d.ts +0 -1
  210. package/dist/scriptRunner.test.js +0 -386
  211. package/dist/secretProviders.test.d.ts +0 -1
  212. package/dist/secretProviders.test.js +0 -726
  213. package/dist/syncConsents.test.d.ts +0 -1
  214. package/dist/syncConsents.test.js +0 -522
  215. package/dist/terrenoApp.test.d.ts +0 -1
  216. package/dist/terrenoApp.test.js +0 -489
  217. package/dist/tests/bunSetup.d.ts +0 -1
  218. package/dist/tests/fixtures/compileAuthEntry.d.ts +0 -1
  219. package/dist/tests/fixtures/compileAuthEntry.js +0 -37
  220. package/dist/tests/testEnv.d.ts +0 -0
  221. package/dist/tests/testEnv.js +0 -6
  222. package/dist/transformers.test.d.ts +0 -1
  223. package/dist/transformers.test.js +0 -423
  224. package/dist/utils.test.d.ts +0 -1
  225. package/dist/utils.test.js +0 -242
  226. /package/dist/{__tests__/openApiCompat.test.d.ts → sync/loadHarness.d.ts} +0 -0
@@ -0,0 +1,272 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __read = (this && this.__read) || function (o, n) {
39
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
40
+ if (!m) return o;
41
+ var i = m.call(o), r, ar = [], e;
42
+ try {
43
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
44
+ }
45
+ catch (error) { e = { error: error }; }
46
+ finally {
47
+ try {
48
+ if (r && !r.done && (m = i["return"])) m.call(i);
49
+ }
50
+ finally { if (e) throw e.error; }
51
+ }
52
+ return ar;
53
+ };
54
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
55
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
56
+ if (ar || !(i in from)) {
57
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
58
+ ar[i] = from[i];
59
+ }
60
+ }
61
+ return to.concat(ar || Array.prototype.slice.call(from));
62
+ };
63
+ var __values = (this && this.__values) || function(o) {
64
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
65
+ if (m) return m.call(o);
66
+ if (o && typeof o.length === "number") return {
67
+ next: function () {
68
+ if (o && i >= o.length) o = void 0;
69
+ return { value: o && o[i++], done: !o };
70
+ }
71
+ };
72
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
73
+ };
74
+ Object.defineProperty(exports, "__esModule", { value: true });
75
+ exports.createSocketAuthMiddleware = exports.createBetterAuthValidator = exports.createLegacyJwtValidator = void 0;
76
+ var socketio_jwt_1 = require("@thream/socketio-jwt");
77
+ var logger_1 = require("../logger");
78
+ var plugins_1 = require("../plugins");
79
+ /**
80
+ * Legacy JWT validator: wraps the `@thream/socketio-jwt` middleware so its observable
81
+ * behavior (token format requirements, secret verification, `decodedToken` payload,
82
+ * `UnauthorizedError` shapes) is identical to the previous direct `io.use(authorize(...))`.
83
+ *
84
+ * D1: `@thream/socketio-jwt`'s `authorize()` has no `issuer` option — it only verifies
85
+ * the signature/algorithm — so without this the socket path silently accepted a
86
+ * validly-signed token issued for a DIFFERENT `TOKEN_ISSUER` (e.g. a token from another
87
+ * environment sharing the same `TOKEN_SECRET`), unlike the HTTP path's
88
+ * `jwt.verify(token, secret, {issuer})`. When `issuer` is provided, the post-verify
89
+ * `onAuthentication` hook checks `decodedToken.iss` and rejects a mismatch with the
90
+ * same `UnauthorizedError` shape the signature-verification failure path uses, so
91
+ * callers cannot distinguish "bad signature" from "wrong issuer" from the error alone
92
+ * (matching the non-disclosure posture the HTTP path also has).
93
+ *
94
+ * `issuer` may be a plain string or a thunk (`() => string | undefined`) resolved on
95
+ * EVERY handshake — the HTTP path's `jwt.verify` reads `process.env.TOKEN_ISSUER` fresh
96
+ * per request rather than once at server startup, and a static string captured once at
97
+ * `RealtimeApp.onServerCreated()` time would go stale if `TOKEN_ISSUER` changes later
98
+ * (e.g. test suites that mutate it between fixtures). Pass a thunk to preserve that
99
+ * per-request freshness; a plain string is still supported for callers who intentionally
100
+ * want a fixed value.
101
+ */
102
+ var createLegacyJwtValidator = function (tokenSecret, issuer) {
103
+ var resolveIssuer = function () {
104
+ return typeof issuer === "function" ? issuer() : issuer;
105
+ };
106
+ var middleware = (0, socketio_jwt_1.authorize)({
107
+ onAuthentication: function (decodedToken) {
108
+ var expectedIssuer = resolveIssuer();
109
+ if (expectedIssuer && (decodedToken === null || decodedToken === void 0 ? void 0 : decodedToken.iss) !== expectedIssuer) {
110
+ throw new socketio_jwt_1.UnauthorizedError("invalid_token", {
111
+ message: "Unauthorized: Token is missing or invalid Bearer",
112
+ });
113
+ }
114
+ },
115
+ secret: tokenSecret,
116
+ });
117
+ return function (socket) {
118
+ return new Promise(function (resolve, reject) {
119
+ // The socketio-jwt middleware types demand a full Socket; it only reads
120
+ // handshake.auth.token and writes encodedToken/decodedToken.
121
+ middleware(socket, function (error) {
122
+ if (error) {
123
+ reject(error);
124
+ return;
125
+ }
126
+ // D1: stamp which validator authenticated this socket so the periodic
127
+ // re-validation sweep knows to re-check local JWT expiry (not a Better Auth
128
+ // session lookup) for it. The library already populated decodedToken with the
129
+ // full JWT payload (exp/iss included), so this only adds the discriminator.
130
+ if (socket.decodedToken) {
131
+ socket.decodedToken.authKind = "jwt";
132
+ }
133
+ resolve();
134
+ });
135
+ });
136
+ };
137
+ };
138
+ exports.createLegacyJwtValidator = createLegacyJwtValidator;
139
+ /** Strip an optional `Bearer ` prefix from the handshake token. */
140
+ var extractRawToken = function (socket) {
141
+ var token = socket.handshake.auth.token;
142
+ if (typeof token !== "string" || token.length === 0) {
143
+ return null;
144
+ }
145
+ var parts = token.split(" ");
146
+ if (parts.length === 2 && parts[0] === "Bearer") {
147
+ return parts[1];
148
+ }
149
+ return token;
150
+ };
151
+ /**
152
+ * Better Auth session validator: treats the handshake token as a Better Auth session token
153
+ * and validates it via `auth.api.getSession` (the same lookup the HTTP session middleware
154
+ * uses). The token is presented both as a bearer Authorization header (for the Better Auth
155
+ * bearer plugin) and as the session cookie, so either transport configuration works.
156
+ */
157
+ var createBetterAuthValidator = function (options) {
158
+ var auth = options.auth, userModel = options.userModel;
159
+ return function (socket) { return __awaiter(void 0, void 0, void 0, function () {
160
+ var rawToken, session, betterAuthUserId, id, admin, appUser;
161
+ var _a;
162
+ return __generator(this, function (_b) {
163
+ switch (_b.label) {
164
+ case 0:
165
+ rawToken = extractRawToken(socket);
166
+ if (!rawToken) {
167
+ throw new socketio_jwt_1.UnauthorizedError("credentials_required", { message: "no token provided" });
168
+ }
169
+ return [4 /*yield*/, auth.api.getSession({
170
+ headers: { authorization: "Bearer ".concat(rawToken) },
171
+ })];
172
+ case 1:
173
+ session = _b.sent();
174
+ betterAuthUserId = (_a = session === null || session === void 0 ? void 0 : session.user) === null || _a === void 0 ? void 0 : _a.id;
175
+ if (!betterAuthUserId) {
176
+ throw new socketio_jwt_1.UnauthorizedError("invalid_token", {
177
+ message: "Unauthorized: Better Auth session is missing or invalid",
178
+ });
179
+ }
180
+ id = String(betterAuthUserId);
181
+ admin = false;
182
+ if (!userModel) return [3 /*break*/, 3];
183
+ return [4 /*yield*/, (0, plugins_1.findOneOrNoneFor)(userModel, {
184
+ betterAuthId: betterAuthUserId,
185
+ })];
186
+ case 2:
187
+ appUser = (_b.sent());
188
+ if (!(appUser === null || appUser === void 0 ? void 0 : appUser._id)) {
189
+ throw new socketio_jwt_1.UnauthorizedError("invalid_token", {
190
+ message: "Unauthorized: Better Auth user has no application user",
191
+ });
192
+ }
193
+ id = String(appUser._id);
194
+ admin = appUser.admin === true;
195
+ _b.label = 3;
196
+ case 3:
197
+ socket.decodedToken = { admin: admin, authKind: "better-auth", id: id, isAnonymous: false };
198
+ // D1: retain the raw session token so the periodic re-validation sweep can re-run
199
+ // `auth.api.getSession` for this socket without re-deriving it from the handshake
200
+ // (which may have since changed if the client reconnected with a new token).
201
+ socket.encodedToken = rawToken;
202
+ return [2 /*return*/];
203
+ }
204
+ });
205
+ }); };
206
+ };
207
+ exports.createBetterAuthValidator = createBetterAuthValidator;
208
+ /**
209
+ * Build the Socket.io auth middleware from a validator chain: validators run in order and
210
+ * the first success wins; when all fail the connection is rejected with the last error.
211
+ */
212
+ var createSocketAuthMiddleware = function (_a) {
213
+ var tokenSecret = _a.tokenSecret, issuer = _a.issuer, betterAuth = _a.betterAuth, _b = _a.extraValidators, extraValidators = _b === void 0 ? [] : _b;
214
+ var validators = [(0, exports.createLegacyJwtValidator)(tokenSecret, issuer)];
215
+ if (betterAuth) {
216
+ validators.push((0, exports.createBetterAuthValidator)(betterAuth));
217
+ }
218
+ validators.push.apply(validators, __spreadArray([], __read(extraValidators), false));
219
+ return function (socket, next) {
220
+ void (function () { return __awaiter(void 0, void 0, void 0, function () {
221
+ var lastError, validators_1, validators_1_1, validator, error_1, e_1_1;
222
+ var e_1, _a;
223
+ return __generator(this, function (_b) {
224
+ switch (_b.label) {
225
+ case 0:
226
+ lastError = new socketio_jwt_1.UnauthorizedError("credentials_required", {
227
+ message: "no token provided",
228
+ });
229
+ _b.label = 1;
230
+ case 1:
231
+ _b.trys.push([1, 8, 9, 10]);
232
+ validators_1 = __values(validators), validators_1_1 = validators_1.next();
233
+ _b.label = 2;
234
+ case 2:
235
+ if (!!validators_1_1.done) return [3 /*break*/, 7];
236
+ validator = validators_1_1.value;
237
+ _b.label = 3;
238
+ case 3:
239
+ _b.trys.push([3, 5, , 6]);
240
+ return [4 /*yield*/, validator(socket)];
241
+ case 4:
242
+ _b.sent();
243
+ next();
244
+ return [2 /*return*/];
245
+ case 5:
246
+ error_1 = _b.sent();
247
+ lastError = error_1 instanceof Error ? error_1 : new Error(String(error_1));
248
+ return [3 /*break*/, 6];
249
+ case 6:
250
+ validators_1_1 = validators_1.next();
251
+ return [3 /*break*/, 2];
252
+ case 7: return [3 /*break*/, 10];
253
+ case 8:
254
+ e_1_1 = _b.sent();
255
+ e_1 = { error: e_1_1 };
256
+ return [3 /*break*/, 10];
257
+ case 9:
258
+ try {
259
+ if (validators_1_1 && !validators_1_1.done && (_a = validators_1.return)) _a.call(validators_1);
260
+ }
261
+ finally { if (e_1) throw e_1.error; }
262
+ return [7 /*endfinally*/];
263
+ case 10:
264
+ logger_1.logger.debug("[realtime] Socket authentication failed: ".concat(lastError.message));
265
+ next(lastError);
266
+ return [2 /*return*/];
267
+ }
268
+ });
269
+ }); })();
270
+ };
271
+ };
272
+ exports.createSocketAuthMiddleware = createSocketAuthMiddleware;
@@ -3,8 +3,62 @@ export interface DecodedRealtimeToken {
3
3
  admin?: boolean;
4
4
  id?: string;
5
5
  isAnonymous?: boolean;
6
+ /** JWT `exp` claim (seconds since epoch) — present for the legacy JWT validator only. */
7
+ exp?: number;
8
+ /** JWT `iss` claim — present for the legacy JWT validator only. */
9
+ iss?: string;
10
+ /**
11
+ * Which validator in the chain authenticated this socket (D1: the periodic
12
+ * re-validation sweep uses this to pick the matching cheap re-check — local JWT
13
+ * expiry verification vs. a Better Auth session lookup). Undefined for handshakes
14
+ * that predate this field (never actually observable at runtime — set by every
15
+ * validator — but kept optional so structural test doubles compile without it).
16
+ */
17
+ authKind?: "jwt" | "better-auth";
18
+ }
19
+ /**
20
+ * Per-socket data bag. `fullUser` is populated once at handshake (see
21
+ * `loadFullUserForSocket` / `RealtimeApp`'s connection handler) by loading the full
22
+ * Mongoose user document for `decodedToken.id`, and refreshed by D1's periodic
23
+ * re-validation sweep. When present it is authoritative for authorization (permits
24
+ * fields like `organizationIds` that the synthetic decoded-token shape never carries
25
+ * — see D2); the synthetic shape remains a fallback for setups with no `userModel`
26
+ * configured, or while the handshake load is still in flight.
27
+ */
28
+ export interface SocketDataBag {
29
+ fullUser?: any;
30
+ /**
31
+ * The in-flight handshake load of {@link SocketDataBag.fullUser}, published so handlers
32
+ * that must not authorize against the synthetic token user can await it
33
+ * (see {@link awaitSocketFullUser}). Never rejects.
34
+ */
35
+ fullUserLoad?: Promise<void>;
36
+ /**
37
+ * Sync collection tag -> joined `sync:{stream}` rooms (see `socketHandlers.ts`).
38
+ * Lives on the data bag (not the handler closure) so D1's sweep can re-resolve
39
+ * stream membership and `socket.leave()` rooms no longer held (D4) without needing
40
+ * access to `installSyncSocketHandlers`'s internal state.
41
+ */
42
+ syncSubscriptions?: Map<string, Set<string>>;
6
43
  }
7
44
  export interface SocketWithDecodedToken {
8
45
  decodedToken?: DecodedRealtimeToken;
46
+ data?: SocketDataBag;
9
47
  }
48
+ /**
49
+ * Resolve the authorization-ready user for a socket: the full user document loaded at
50
+ * handshake (`socket.data.fullUser`, see D2) when available, otherwise the synthetic
51
+ * `{_id, admin, id, isAnonymous}` shape derived from the decoded token alone. Consumers
52
+ * (permission checks, `getUserScopes`, delta filters) should always go through this
53
+ * function rather than reading `decodedToken` directly, so they transparently benefit
54
+ * once a `userModel` is configured.
55
+ */
10
56
  export declare const getSocketUser: (socket: SocketWithDecodedToken) => User | undefined;
57
+ /**
58
+ * Task 9.21: {@link getSocketUser}, but first awaiting the handshake full-user load when it
59
+ * is still in flight. Sync handlers use this so a `sync:subscribe` / `sync:mutate` that
60
+ * lands inside the handshake window is authorized against the same user every later event
61
+ * sees — scope membership must not depend on event timing. Falls back to the synthetic
62
+ * token user exactly as `getSocketUser` does when no `userModel` is configured.
63
+ */
64
+ export declare const awaitSocketFullUser: (socket: SocketWithDecodedToken) => Promise<User | undefined>;
@@ -1,17 +1,87 @@
1
1
  "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
2
38
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getSocketUser = void 0;
39
+ exports.awaitSocketFullUser = exports.getSocketUser = void 0;
40
+ /**
41
+ * Resolve the authorization-ready user for a socket: the full user document loaded at
42
+ * handshake (`socket.data.fullUser`, see D2) when available, otherwise the synthetic
43
+ * `{_id, admin, id, isAnonymous}` shape derived from the decoded token alone. Consumers
44
+ * (permission checks, `getUserScopes`, delta filters) should always go through this
45
+ * function rather than reading `decodedToken` directly, so they transparently benefit
46
+ * once a `userModel` is configured.
47
+ */
4
48
  var getSocketUser = function (socket) {
5
- var _a, _b, _c;
6
- var userId = (_a = socket.decodedToken) === null || _a === void 0 ? void 0 : _a.id;
49
+ var _a, _b, _c, _d;
50
+ var fullUser = (_a = socket.data) === null || _a === void 0 ? void 0 : _a.fullUser;
51
+ if (fullUser) {
52
+ return fullUser;
53
+ }
54
+ var userId = (_b = socket.decodedToken) === null || _b === void 0 ? void 0 : _b.id;
7
55
  if (!userId) {
8
56
  return undefined;
9
57
  }
10
58
  return {
11
59
  _id: userId,
12
- admin: ((_b = socket.decodedToken) === null || _b === void 0 ? void 0 : _b.admin) === true,
60
+ admin: ((_c = socket.decodedToken) === null || _c === void 0 ? void 0 : _c.admin) === true,
13
61
  id: userId,
14
- isAnonymous: (_c = socket.decodedToken) === null || _c === void 0 ? void 0 : _c.isAnonymous,
62
+ isAnonymous: (_d = socket.decodedToken) === null || _d === void 0 ? void 0 : _d.isAnonymous,
15
63
  };
16
64
  };
17
65
  exports.getSocketUser = getSocketUser;
66
+ /**
67
+ * Task 9.21: {@link getSocketUser}, but first awaiting the handshake full-user load when it
68
+ * is still in flight. Sync handlers use this so a `sync:subscribe` / `sync:mutate` that
69
+ * lands inside the handshake window is authorized against the same user every later event
70
+ * sees — scope membership must not depend on event timing. Falls back to the synthetic
71
+ * token user exactly as `getSocketUser` does when no `userModel` is configured.
72
+ */
73
+ var awaitSocketFullUser = function (socket) { return __awaiter(void 0, void 0, void 0, function () {
74
+ var _a;
75
+ return __generator(this, function (_b) {
76
+ switch (_b.label) {
77
+ case 0:
78
+ // The load swallows and logs its own failures; this await only orders the events.
79
+ return [4 /*yield*/, ((_a = socket.data) === null || _a === void 0 ? void 0 : _a.fullUserLoad)];
80
+ case 1:
81
+ // The load swallows and logs its own failures; this await only orders the events.
82
+ _b.sent();
83
+ return [2 /*return*/, (0, exports.getSocketUser)(socket)];
84
+ }
85
+ });
86
+ }); };
87
+ exports.awaitSocketFullUser = awaitSocketFullUser;
@@ -1,4 +1,7 @@
1
1
  import type express from "express";
2
+ import type { UserModel } from "../auth";
3
+ import type { SyncAppOptions } from "../sync/routes";
4
+ import type { BetterAuthSocketOptions } from "./socketAuth";
2
5
  /**
3
6
  * Configuration for real-time sync on a modelRouter.
4
7
  * Determines which CRUD methods emit WebSocket events and how they are routed.
@@ -75,6 +78,43 @@ export interface RealtimeAppOptions {
75
78
  redisUrl?: string;
76
79
  /** JWT secret for socket authentication (default: process.env.TOKEN_SECRET) */
77
80
  tokenSecret?: string;
81
+ /**
82
+ * JWT issuer required for socket authentication (default: process.env.TOKEN_ISSUER),
83
+ * for parity with the HTTP JWT path's `jwt.verify(token, secret, {issuer})` (D1).
84
+ * Omit (and leave `TOKEN_ISSUER` unset) to skip the issuer check.
85
+ */
86
+ tokenIssuer?: string;
87
+ /**
88
+ * Enables the Better Auth session validator for socket authentication, tried after the
89
+ * legacy JWT validator. Pass the instance returned by `createBetterAuth` (and optionally
90
+ * the app user model so `decodedToken.id`/`admin` match the REST identity).
91
+ */
92
+ betterAuth?: BetterAuthSocketOptions;
93
+ /**
94
+ * Explicit SyncAppOptions override for the sync socket handlers. Normally omitted —
95
+ * the options registered by the SyncApp plugin are used automatically.
96
+ */
97
+ sync?: SyncAppOptions;
98
+ /**
99
+ * The application's Mongoose user model. When provided, the full user document is
100
+ * loaded once at handshake (by the decoded token's id) and cached on
101
+ * `socket.data.fullUser`, then refreshed by the periodic session re-validation sweep
102
+ * (D1). Authorization for realtime/sync subscriptions and mutations uses this full
103
+ * document instead of the synthetic `{_id, admin, id}` shape derived from the token
104
+ * alone — required for any permission check or `getUserScopes` resolver that reads
105
+ * fields beyond `admin` (e.g. `organizationIds` for tenant-scoped sync). Without it,
106
+ * socket-side authorization falls back to the synthetic shape (pre-D2 behavior).
107
+ */
108
+ userModel?: UserModel;
109
+ /**
110
+ * Interval in ms for the periodic socket session re-validation sweep (D1): re-checks
111
+ * JWT expiry / Better Auth session validity and the user's `disabled` flag for every
112
+ * connected socket, disconnecting (`sync:auth-expired` then `disconnect(true)`) any
113
+ * socket that fails. Also refreshes `socket.data.fullUser` (D2) and re-resolves sync
114
+ * stream membership, leaving rooms for streams no longer held (D4). Default 60_000ms;
115
+ * set to 0 to disable the sweep entirely (e.g. in tests).
116
+ */
117
+ sessionRevalidationIntervalMs?: number;
78
118
  /** Enable debug logging */
79
119
  debug?: boolean;
80
120
  }
@@ -1,4 +1,19 @@
1
1
  import type { SecretProvider } from "./configurationPlugin";
2
+ interface SecretManagerClient {
3
+ accessSecretVersion(request: {
4
+ name: string;
5
+ }): Promise<[{
6
+ payload?: {
7
+ data?: string | Uint8Array;
8
+ };
9
+ }]>;
10
+ }
11
+ interface SecretManagerModule {
12
+ SecretManagerServiceClient?: new () => SecretManagerClient;
13
+ default?: {
14
+ SecretManagerServiceClient?: new () => SecretManagerClient;
15
+ };
16
+ }
2
17
  /**
3
18
  * Secret provider that reads secrets from environment variables.
4
19
  * Useful for local development and testing.
@@ -27,6 +42,12 @@ export declare class EnvSecretProvider implements SecretProvider {
27
42
  export interface GcpSecretProviderOptions {
28
43
  /** GCP project ID. Required for short secret names. */
29
44
  projectId: string;
45
+ /**
46
+ * Loads the optional `@google-cloud/secret-manager` peer. Overridable so tests can exercise
47
+ * the "peer not installed" path without depending on whether the install layout happens to
48
+ * expose the package.
49
+ */
50
+ loadModule?: () => Promise<SecretManagerModule>;
30
51
  }
31
52
  /**
32
53
  * Secret provider that reads secrets from Google Cloud Secret Manager.
@@ -45,6 +66,7 @@ export declare class GcpSecretProvider implements SecretProvider {
45
66
  name: string;
46
67
  private projectId;
47
68
  private client;
69
+ private loadModule;
48
70
  constructor(options: GcpSecretProviderOptions);
49
71
  private getClient;
50
72
  /**
@@ -122,3 +144,4 @@ export declare class CachingSecretProvider implements SecretProvider {
122
144
  /** Invalidates a single cached secret by name (and optional version). */
123
145
  clearKey(secretName: string, version?: string): void;
124
146
  }
147
+ export {};
@@ -154,13 +154,20 @@ exports.EnvSecretProvider = EnvSecretProvider;
154
154
  */
155
155
  var GcpSecretProvider = /** @class */ (function () {
156
156
  function GcpSecretProvider(options) {
157
+ var _a;
157
158
  this.name = "gcp";
158
159
  this.client = null;
159
160
  this.projectId = options.projectId;
161
+ this.loadModule =
162
+ (_a = options.loadModule) !== null && _a !== void 0 ? _a : (function () {
163
+ // Dynamic import — @google-cloud/secret-manager is an optional peer dependency
164
+ var moduleName = "@google-cloud/secret-manager";
165
+ return Promise.resolve("".concat(/* webpackIgnore: true */ moduleName)).then(function (s) { return __importStar(require(s)); });
166
+ });
160
167
  }
161
168
  GcpSecretProvider.prototype.getClient = function () {
162
169
  return __awaiter(this, void 0, void 0, function () {
163
- var mod, moduleName, _a, SecretManagerServiceClient;
170
+ var mod, _a, SecretManagerServiceClient;
164
171
  var _b, _c;
165
172
  return __generator(this, function (_d) {
166
173
  switch (_d.label) {
@@ -170,8 +177,7 @@ var GcpSecretProvider = /** @class */ (function () {
170
177
  _d.label = 1;
171
178
  case 1:
172
179
  _d.trys.push([1, 3, , 4]);
173
- moduleName = "@google-cloud/secret-manager";
174
- return [4 /*yield*/, Promise.resolve("".concat(/* webpackIgnore: true */ moduleName)).then(function (s) { return __importStar(require(s)); })];
180
+ return [4 /*yield*/, this.loadModule()];
175
181
  case 2:
176
182
  mod = _d.sent();
177
183
  return [3 /*break*/, 4];