@hot-updater/server 1.0.0-rc.2 → 1.0.0-rc.21

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 (328) hide show
  1. package/LICENSE +12 -14
  2. package/dist/adapters/drizzle.cjs +32 -75
  3. package/dist/adapters/drizzle.d.cts +13 -5
  4. package/dist/adapters/drizzle.d.mts +13 -5
  5. package/dist/adapters/drizzle.mjs +32 -77
  6. package/dist/adapters/drizzleExecutor.cjs +114 -0
  7. package/dist/adapters/drizzleExecutor.d.cts +9 -0
  8. package/dist/adapters/drizzleExecutor.d.mts +9 -0
  9. package/dist/adapters/drizzleExecutor.mjs +112 -0
  10. package/dist/adapters/kysely.cjs +22 -31
  11. package/dist/adapters/kysely.d.cts +10 -6
  12. package/dist/adapters/kysely.d.mts +10 -6
  13. package/dist/adapters/kysely.mjs +23 -33
  14. package/dist/adapters/kyselyExecutor.cjs +32 -0
  15. package/dist/adapters/kyselyExecutor.d.cts +11 -0
  16. package/dist/adapters/kyselyExecutor.d.mts +11 -0
  17. package/dist/adapters/kyselyExecutor.mjs +32 -0
  18. package/dist/adapters/mongodb.cjs +18 -54
  19. package/dist/adapters/mongodb.d.cts +10 -5
  20. package/dist/adapters/mongodb.d.mts +10 -5
  21. package/dist/adapters/mongodb.mjs +19 -56
  22. package/dist/adapters/mongodbAdapter.cjs +192 -0
  23. package/dist/adapters/mongodbAdapter.d.cts +9 -0
  24. package/dist/adapters/mongodbAdapter.d.mts +9 -0
  25. package/dist/adapters/mongodbAdapter.mjs +191 -0
  26. package/dist/adapters/prisma.cjs +35 -267
  27. package/dist/adapters/prisma.d.cts +12 -7
  28. package/dist/adapters/prisma.d.mts +12 -7
  29. package/dist/adapters/prisma.mjs +36 -268
  30. package/dist/adapters/prismaExecutor.cjs +63 -0
  31. package/dist/adapters/prismaExecutor.mjs +63 -0
  32. package/dist/adapters/sqlProviders.cjs +14 -0
  33. package/dist/adapters/sqlProviders.mjs +14 -0
  34. package/dist/assembly/assemblePlugins.cjs +144 -0
  35. package/dist/assembly/assemblePlugins.d.cts +5 -0
  36. package/dist/assembly/assemblePlugins.d.mts +5 -0
  37. package/dist/assembly/assemblePlugins.mjs +139 -0
  38. package/dist/assembly/clientPlugins.cjs +88 -0
  39. package/dist/assembly/clientPlugins.mjs +88 -0
  40. package/dist/assembly/configError.d.cts +2 -0
  41. package/dist/assembly/configError.d.mts +2 -0
  42. package/dist/assembly/configError.mjs +2 -0
  43. package/dist/core/api.cjs +51 -0
  44. package/dist/core/api.d.cts +54 -0
  45. package/dist/core/api.d.mts +54 -0
  46. package/dist/core/api.mjs +51 -0
  47. package/dist/core/baseCandidates.cjs +28 -0
  48. package/dist/core/baseCandidates.mjs +28 -0
  49. package/dist/core/operations.cjs +351 -0
  50. package/dist/core/operations.mjs +351 -0
  51. package/dist/core/reads.cjs +273 -0
  52. package/dist/core/reads.d.cts +9 -0
  53. package/dist/core/reads.d.mts +9 -0
  54. package/dist/core/reads.mjs +267 -0
  55. package/dist/core/releases.cjs +193 -0
  56. package/dist/core/releases.mjs +190 -0
  57. package/dist/core/writes.cjs +96 -0
  58. package/dist/core/writes.mjs +91 -0
  59. package/dist/createHotUpdaterCore.cjs +72 -91
  60. package/dist/createHotUpdaterCore.d.cts +106 -38
  61. package/dist/createHotUpdaterCore.d.mts +106 -38
  62. package/dist/createHotUpdaterCore.mjs +74 -89
  63. package/dist/db/engineDrizzleSchema.cjs +53 -0
  64. package/dist/db/engineDrizzleSchema.mjs +53 -0
  65. package/dist/db/enginePrismaSchema.cjs +84 -0
  66. package/dist/db/enginePrismaSchema.d.cts +5 -0
  67. package/dist/db/enginePrismaSchema.d.mts +5 -0
  68. package/dist/db/enginePrismaSchema.mjs +83 -0
  69. package/dist/db/releaseCatalog.cjs +24 -47
  70. package/dist/db/releaseCatalog.mjs +20 -44
  71. package/dist/db/updateArtifacts.cjs +43 -72
  72. package/dist/db/updateArtifacts.mjs +40 -69
  73. package/dist/handler.cjs +59 -43
  74. package/dist/handler.d.cts +3 -5
  75. package/dist/handler.d.mts +3 -5
  76. package/dist/handler.mjs +61 -43
  77. package/dist/handlerAdminRoutes.cjs +374 -0
  78. package/dist/handlerAdminRoutes.mjs +372 -0
  79. package/dist/handlerParameters.cjs +6 -11
  80. package/dist/handlerParameters.mjs +6 -10
  81. package/dist/handlerReleaseCatalogRoutes.cjs +32 -15
  82. package/dist/handlerReleaseCatalogRoutes.mjs +32 -15
  83. package/dist/handlerTypes.d.cts +2 -55
  84. package/dist/handlerTypes.d.mts +2 -55
  85. package/dist/handlerVersionRoutes.cjs +20 -4
  86. package/dist/handlerVersionRoutes.mjs +20 -4
  87. package/dist/index.cjs +9 -9
  88. package/dist/index.d.cts +8 -9
  89. package/dist/index.d.mts +8 -9
  90. package/dist/index.mjs +3 -4
  91. package/dist/node.cjs +3 -6
  92. package/dist/node.d.cts +2 -2
  93. package/dist/node.d.mts +2 -2
  94. package/dist/node.mjs +4 -4
  95. package/dist/package.cjs +1 -1
  96. package/dist/package.mjs +1 -1
  97. package/dist/plugins/api-keys/index.cjs +9 -0
  98. package/dist/plugins/api-keys/index.d.cts +1 -0
  99. package/dist/plugins/api-keys/index.d.mts +1 -0
  100. package/dist/plugins/api-keys/index.mjs +2 -0
  101. package/dist/plugins/definePlugin.d.cts +2 -0
  102. package/dist/plugins/definePlugin.d.mts +2 -0
  103. package/dist/plugins/insights/index.cjs +9 -0
  104. package/dist/plugins/insights/index.d.cts +1 -0
  105. package/dist/plugins/insights/index.d.mts +1 -0
  106. package/dist/plugins/insights/index.mjs +2 -0
  107. package/dist/plugins/official.cjs +30 -0
  108. package/dist/plugins/official.mjs +29 -0
  109. package/dist/storageAccess.cjs +13 -10
  110. package/dist/storageAccess.mjs +13 -10
  111. package/dist/types/index.d.cts +2 -28
  112. package/dist/types/index.d.mts +2 -28
  113. package/package.json +26 -14
  114. package/dist/_virtual/_rolldown/runtime.cjs +0 -23
  115. package/dist/adapters/databaseConstraintErrors.cjs +0 -22
  116. package/dist/adapters/databaseConstraintErrors.mjs +0 -21
  117. package/dist/adapters/databasePluginUtils.cjs +0 -116
  118. package/dist/adapters/databasePluginUtils.mjs +0 -106
  119. package/dist/adapters/drizzleCrud.cjs +0 -311
  120. package/dist/adapters/drizzleCrud.mjs +0 -308
  121. package/dist/adapters/drizzleLazyDB.cjs +0 -106
  122. package/dist/adapters/drizzleLazyDB.mjs +0 -106
  123. package/dist/adapters/drizzleQuery.cjs +0 -69
  124. package/dist/adapters/drizzleQuery.mjs +0 -69
  125. package/dist/adapters/insightsTransaction.cjs +0 -22
  126. package/dist/adapters/insightsTransaction.mjs +0 -22
  127. package/dist/adapters/kyselyCrud.cjs +0 -305
  128. package/dist/adapters/kyselyCrud.mjs +0 -304
  129. package/dist/adapters/kyselyQuery.cjs +0 -56
  130. package/dist/adapters/kyselyQuery.mjs +0 -56
  131. package/dist/adapters/mongodbCollections.cjs +0 -38
  132. package/dist/adapters/mongodbCollections.mjs +0 -32
  133. package/dist/adapters/mongodbQuery.cjs +0 -94
  134. package/dist/adapters/mongodbQuery.mjs +0 -86
  135. package/dist/adapters/mongodbReads.cjs +0 -210
  136. package/dist/adapters/mongodbReads.mjs +0 -210
  137. package/dist/adapters/mongodbWrites.cjs +0 -148
  138. package/dist/adapters/mongodbWrites.mjs +0 -148
  139. package/dist/adapters/prismaQuery.cjs +0 -57
  140. package/dist/adapters/prismaQuery.mjs +0 -56
  141. package/dist/adapters/prismaRows.cjs +0 -219
  142. package/dist/adapters/prismaRows.mjs +0 -209
  143. package/dist/apiKeys.cjs +0 -143
  144. package/dist/apiKeys.d.cts +0 -49
  145. package/dist/apiKeys.d.mts +0 -49
  146. package/dist/apiKeys.mjs +0 -133
  147. package/dist/db/createBundleDiff.cjs +0 -144
  148. package/dist/db/createBundleDiff.d.cts +0 -16
  149. package/dist/db/createBundleDiff.d.mts +0 -16
  150. package/dist/db/createBundleDiff.mjs +0 -141
  151. package/dist/db/databasePluginCore.cjs +0 -137
  152. package/dist/db/databasePluginCore.mjs +0 -137
  153. package/dist/db/fixedMigrator.cjs +0 -79
  154. package/dist/db/fixedMigrator.mjs +0 -78
  155. package/dist/db/fixedMigratorMongo.cjs +0 -321
  156. package/dist/db/fixedMigratorMongo.mjs +0 -321
  157. package/dist/db/fixedMigratorShared.cjs +0 -23
  158. package/dist/db/fixedMigratorShared.mjs +0 -18
  159. package/dist/db/index.cjs +0 -27
  160. package/dist/db/index.d.cts +0 -12
  161. package/dist/db/index.d.mts +0 -12
  162. package/dist/db/index.mjs +0 -22
  163. package/dist/db/mongoMigrationExecution.cjs +0 -11
  164. package/dist/db/mongoMigrationExecution.mjs +0 -11
  165. package/dist/db/releaseCatalog.d.cts +0 -16
  166. package/dist/db/releaseCatalog.d.mts +0 -16
  167. package/dist/db/schema/insightsCollation.cjs +0 -14
  168. package/dist/db/schema/insightsCollation.mjs +0 -14
  169. package/dist/db/schema/mongodb.cjs +0 -25
  170. package/dist/db/schema/mongodb.mjs +0 -25
  171. package/dist/db/schema/registry.cjs +0 -21
  172. package/dist/db/schema/registry.mjs +0 -17
  173. package/dist/db/schema/sql.cjs +0 -105
  174. package/dist/db/schema/sql.mjs +0 -97
  175. package/dist/db/schema/sqlOperations.cjs +0 -27
  176. package/dist/db/schema/sqlOperations.mjs +0 -26
  177. package/dist/db/schemaGenerators.cjs +0 -275
  178. package/dist/db/schemaGenerators.mjs +0 -273
  179. package/dist/db/schemaReadiness.cjs +0 -26
  180. package/dist/db/schemaReadiness.d.cts +0 -9
  181. package/dist/db/schemaReadiness.d.mts +0 -9
  182. package/dist/db/schemaReadiness.mjs +0 -25
  183. package/dist/db/sqlMigrationExecution.cjs +0 -67
  184. package/dist/db/sqlMigrationExecution.mjs +0 -67
  185. package/dist/db/types.cjs +0 -22
  186. package/dist/db/types.d.cts +0 -118
  187. package/dist/db/types.d.mts +0 -118
  188. package/dist/db/types.mjs +0 -19
  189. package/dist/handlerBundleRoutes.cjs +0 -155
  190. package/dist/handlerBundleRoutes.mjs +0 -155
  191. package/dist/handlerReleaseManagementRoutes.cjs +0 -124
  192. package/dist/handlerReleaseManagementRoutes.mjs +0 -124
  193. package/dist/insights/domain.d.cts +0 -89
  194. package/dist/insights/domain.d.mts +0 -89
  195. package/dist/insights/errors.cjs +0 -15
  196. package/dist/insights/errors.mjs +0 -14
  197. package/dist/insights/eventInput.cjs +0 -155
  198. package/dist/insights/eventInput.mjs +0 -153
  199. package/dist/insights/provider.cjs +0 -314
  200. package/dist/insights/provider.d.cts +0 -6
  201. package/dist/insights/provider.d.mts +0 -6
  202. package/dist/insights/provider.mjs +0 -314
  203. package/dist/insights/queryInput.cjs +0 -93
  204. package/dist/insights/queryInput.mjs +0 -91
  205. package/dist/insights/routes.cjs +0 -58
  206. package/dist/insights/routes.mjs +0 -56
  207. package/dist/insights/types.d.cts +0 -32
  208. package/dist/insights/types.d.mts +0 -32
  209. package/dist/schema/dsl.cjs +0 -103
  210. package/dist/schema/dsl.mjs +0 -87
  211. package/dist/schema/index.cjs +0 -20
  212. package/dist/schema/index.mjs +0 -7
  213. package/dist/schema/settings.cjs +0 -9
  214. package/dist/schema/settings.mjs +0 -9
  215. package/dist/schema/types.cjs +0 -8
  216. package/dist/schema/types.mjs +0 -6
  217. package/dist/schema/v1_0_0.cjs +0 -406
  218. package/dist/schema/v1_0_0.mjs +0 -398
  219. package/src/adapters/databaseConstraintErrors.ts +0 -25
  220. package/src/adapters/databasePluginTestDatabase.ts +0 -120
  221. package/src/adapters/databasePluginUtils.spec.ts +0 -29
  222. package/src/adapters/databasePluginUtils.ts +0 -214
  223. package/src/adapters/drizzle.spec.ts +0 -336
  224. package/src/adapters/drizzle.ts +0 -162
  225. package/src/adapters/drizzleCrud.ts +0 -571
  226. package/src/adapters/drizzleLazyDB.ts +0 -271
  227. package/src/adapters/drizzleQuery.ts +0 -164
  228. package/src/adapters/insightsTransaction.ts +0 -32
  229. package/src/adapters/kysely.spec.ts +0 -174
  230. package/src/adapters/kysely.ts +0 -110
  231. package/src/adapters/kyselyCrud.ts +0 -709
  232. package/src/adapters/kyselyQuery.ts +0 -128
  233. package/src/adapters/mongodb.integration.spec.ts +0 -210
  234. package/src/adapters/mongodb.spec.ts +0 -209
  235. package/src/adapters/mongodb.ts +0 -138
  236. package/src/adapters/mongodbCollections.ts +0 -67
  237. package/src/adapters/mongodbQuery.ts +0 -255
  238. package/src/adapters/mongodbReads.ts +0 -380
  239. package/src/adapters/mongodbRows.spec.ts +0 -64
  240. package/src/adapters/mongodbRows.ts +0 -118
  241. package/src/adapters/mongodbTestClient.ts +0 -377
  242. package/src/adapters/mongodbTestFilter.ts +0 -169
  243. package/src/adapters/mongodbWrites.ts +0 -287
  244. package/src/adapters/prisma.spec.ts +0 -293
  245. package/src/adapters/prisma.ts +0 -565
  246. package/src/adapters/prismaQuery.ts +0 -129
  247. package/src/adapters/prismaRows.spec.ts +0 -98
  248. package/src/adapters/prismaRows.ts +0 -337
  249. package/src/adapters/prismaTestClient.ts +0 -413
  250. package/src/apiKeys.integration.spec.ts +0 -192
  251. package/src/apiKeys.spec.ts +0 -162
  252. package/src/apiKeys.ts +0 -220
  253. package/src/calculatePagination.ts +0 -34
  254. package/src/createHotUpdaterCore.ts +0 -246
  255. package/src/db/bundleRows.spec.ts +0 -164
  256. package/src/db/bundleRows.ts +0 -10
  257. package/src/db/createBundleDiff.spec.ts +0 -450
  258. package/src/db/createBundleDiff.ts +0 -364
  259. package/src/db/databasePluginCore.spec.ts +0 -62
  260. package/src/db/databasePluginCore.testFixtures.ts +0 -76
  261. package/src/db/databasePluginCore.ts +0 -185
  262. package/src/db/databasePluginUpdateCheck.bench.ts +0 -110
  263. package/src/db/fixedMigrator.spec.ts +0 -296
  264. package/src/db/fixedMigrator.ts +0 -147
  265. package/src/db/fixedMigratorMongo.spec.ts +0 -239
  266. package/src/db/fixedMigratorMongo.ts +0 -425
  267. package/src/db/fixedMigratorShared.ts +0 -36
  268. package/src/db/hotUpdaterSchema.ts +0 -5
  269. package/src/db/index.spec.ts +0 -1269
  270. package/src/db/index.ts +0 -47
  271. package/src/db/mongoMigrationExecution.ts +0 -23
  272. package/src/db/node-sqlite.d.ts +0 -25
  273. package/src/db/releaseCatalog.ts +0 -148
  274. package/src/db/schema/definitions.ts +0 -1
  275. package/src/db/schema/insightsCollation.ts +0 -21
  276. package/src/db/schema/mongodb.ts +0 -40
  277. package/src/db/schema/registry.ts +0 -55
  278. package/src/db/schema/sql.ts +0 -244
  279. package/src/db/schema/sqlOperations.ts +0 -63
  280. package/src/db/schema/types.ts +0 -1
  281. package/src/db/schemaGenerators.ts +0 -494
  282. package/src/db/schemaReadiness.ts +0 -34
  283. package/src/db/sqlMigrationExecution.spec.ts +0 -65
  284. package/src/db/sqlMigrationExecution.ts +0 -108
  285. package/src/db/types.spec.ts +0 -63
  286. package/src/db/types.ts +0 -228
  287. package/src/db/updateArtifacts.spec.ts +0 -359
  288. package/src/db/updateArtifacts.ts +0 -541
  289. package/src/handler-standalone.integration.spec.ts +0 -528
  290. package/src/handler.spec.ts +0 -190
  291. package/src/handler.testFixtures.ts +0 -30
  292. package/src/handler.ts +0 -245
  293. package/src/handlerAuth.integration.spec.ts +0 -33
  294. package/src/handlerBundleRoutes.ts +0 -259
  295. package/src/handlerErrors.ts +0 -7
  296. package/src/handlerManagement.spec.ts +0 -262
  297. package/src/handlerParameters.ts +0 -105
  298. package/src/handlerReleaseCatalogRoutes.ts +0 -154
  299. package/src/handlerReleaseManagementRoutes.ts +0 -213
  300. package/src/handlerTypes.ts +0 -96
  301. package/src/handlerVersionRoutes.ts +0 -12
  302. package/src/index.ts +0 -30
  303. package/src/insights/domain.ts +0 -103
  304. package/src/insights/errors.ts +0 -11
  305. package/src/insights/eventInput.ts +0 -225
  306. package/src/insights/insights.integration.spec.ts +0 -381
  307. package/src/insights/provider.spec.ts +0 -385
  308. package/src/insights/provider.ts +0 -591
  309. package/src/insights/queryInput.ts +0 -141
  310. package/src/insights/routes.ts +0 -104
  311. package/src/insights/types.ts +0 -55
  312. package/src/internalRouter.ts +0 -104
  313. package/src/node.spec.ts +0 -119
  314. package/src/node.ts +0 -111
  315. package/src/releaseCatalogRoutes.integration.spec.ts +0 -238
  316. package/src/runtime.spec.ts +0 -194
  317. package/src/runtime.testFixtures.ts +0 -71
  318. package/src/schema/dsl-all-versions.spec.ts +0 -37
  319. package/src/schema/dsl.ts +0 -187
  320. package/src/schema/index.ts +0 -10
  321. package/src/schema/settings.ts +0 -15
  322. package/src/schema/types.ts +0 -79
  323. package/src/schema/v1_0_0.spec.ts +0 -220
  324. package/src/schema/v1_0_0.ts +0 -529
  325. package/src/storageAccess.spec.ts +0 -152
  326. package/src/storageAccess.ts +0 -141
  327. package/src/types/index.ts +0 -34
  328. package/src/version.ts +0 -3
@@ -1,162 +0,0 @@
1
- import { describe, expect, it, vi } from "vitest";
2
-
3
- import { createInMemoryDatabasePlugin } from "../../test-utils/test/inMemoryDatabasePlugin";
4
- import {
5
- API_KEY_HEADER_NAME,
6
- authenticateApiKey,
7
- createApiKey,
8
- createApiKeyManagement,
9
- hashApiKey,
10
- normalizeApiKeyHeaderName,
11
- provisionApiKey,
12
- registerApiKey,
13
- } from "./apiKeys";
14
-
15
- const API_KEY = "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE";
16
-
17
- describe("API keys", () => {
18
- it("normalizes valid header names and rejects invalid names", () => {
19
- expect(normalizeApiKeyHeaderName()).toBe("x-api-key");
20
- expect(normalizeApiKeyHeaderName("X-Hot-Updater-Key")).toBe(
21
- "x-hot-updater-key",
22
- );
23
- expect(() => normalizeApiKeyHeaderName("")).toThrow(
24
- "clientAccess.headerName must be a valid header name.",
25
- );
26
- expect(() => normalizeApiKeyHeaderName("invalid header")).toThrow(
27
- "clientAccess.headerName must be a valid header name.",
28
- );
29
- });
30
-
31
- it("persists only the digest and metadata for a registered key", async () => {
32
- const database = createInMemoryDatabasePlugin();
33
-
34
- const created = await registerApiKey({
35
- apiKeys: database.models.apiKeys,
36
- apiKey: API_KEY,
37
- createdAtMs: 100,
38
- name: " Production app ",
39
- });
40
-
41
- expect(created.apiKey).toBe(API_KEY);
42
- expect(created.record).toEqual({
43
- created_at_ms: 100,
44
- id: expect.stringMatching(/^api-[A-Za-z0-9_-]{22}$/u),
45
- name: "Production app",
46
- prefix: "AQEBAQ",
47
- revoked_at_ms: null,
48
- role: "client",
49
- });
50
- expect(created.record).not.toHaveProperty("hash");
51
- expect(created.record.id).not.toContain(await hashApiKey(API_KEY));
52
- expect(await database.models.apiKeys.list()).toEqual([
53
- expect.objectContaining({ hash: await hashApiKey(API_KEY) }),
54
- ]);
55
- expect(JSON.stringify(await database.models.apiKeys.list())).not.toContain(
56
- API_KEY,
57
- );
58
-
59
- const registeredAgain = await registerApiKey({
60
- apiKeys: database.models.apiKeys,
61
- apiKey: API_KEY,
62
- createdAtMs: 200,
63
- name: "Ignored replacement name",
64
- });
65
- expect(registeredAgain.record).toEqual(created.record);
66
- expect(await database.models.apiKeys.list()).toHaveLength(1);
67
- });
68
-
69
- it("authenticates only active keys after the readiness check", async () => {
70
- const database = createInMemoryDatabasePlugin();
71
- const beforeLookup = vi.fn(async () => undefined);
72
- const { record } = await registerApiKey({
73
- apiKeys: database.models.apiKeys,
74
- apiKey: API_KEY,
75
- name: "App",
76
- });
77
- const request = new Request("https://example.com", {
78
- headers: { [API_KEY_HEADER_NAME]: API_KEY },
79
- });
80
-
81
- await expect(
82
- authenticateApiKey({
83
- apiKeys: database.models.apiKeys,
84
- beforeLookup,
85
- request,
86
- }),
87
- ).resolves.toBe(true);
88
- expect(beforeLookup).toHaveBeenCalledOnce();
89
-
90
- await database.models.apiKeys.revoke({
91
- id: record.id,
92
- revokedAtMs: Date.now(),
93
- });
94
- await expect(
95
- authenticateApiKey({
96
- apiKeys: database.models.apiKeys,
97
- request,
98
- }),
99
- ).resolves.toBe(false);
100
- });
101
-
102
- it("creates a canonical key and validates visible names", async () => {
103
- const database = createInMemoryDatabasePlugin();
104
-
105
- const created = await createApiKey({
106
- apiKeys: database.models.apiKeys,
107
- name: "App",
108
- });
109
-
110
- expect(created.apiKey).toMatch(/^[A-Za-z0-9_-]{43}$/u);
111
- expect(created.record.prefix).toBe(created.apiKey.slice(0, 6));
112
- await expect(
113
- registerApiKey({
114
- apiKeys: database.models.apiKeys,
115
- apiKey: API_KEY,
116
- name: " ",
117
- }),
118
- ).rejects.toThrow("1-64 visible characters");
119
- });
120
-
121
- it("provisions a new key once and reuses an existing managed key", async () => {
122
- const database = createInMemoryDatabasePlugin();
123
-
124
- const created = await provisionApiKey({
125
- apiKeys: database.models.apiKeys,
126
- name: "Managed init",
127
- });
128
- const reused = await provisionApiKey({
129
- apiKeys: database.models.apiKeys,
130
- existingApiKey: created.apiKey,
131
- name: "Managed init rerun",
132
- });
133
-
134
- expect(reused).toEqual(created);
135
- expect(await database.models.apiKeys.list()).toHaveLength(1);
136
- });
137
-
138
- it("manages keys without exposing stored hashes", async () => {
139
- const database = createInMemoryDatabasePlugin();
140
- const beforeOperation = vi.fn(async () => undefined);
141
- const apiKeys = createApiKeyManagement({
142
- apiKeys: database.models.apiKeys,
143
- beforeOperation,
144
- });
145
-
146
- const created = await apiKeys.create({ name: "Production app" });
147
- expect(created.apiKey).toMatch(/^[A-Za-z0-9_-]{43}$/u);
148
- expect(created.record).not.toHaveProperty("hash");
149
-
150
- const records = await apiKeys.list();
151
- expect(records).toEqual([created.record]);
152
- expect(records[0]).not.toHaveProperty("hash");
153
-
154
- const revoked = await apiKeys.revoke({ id: created.record.id });
155
- expect(revoked).toMatchObject({
156
- id: created.record.id,
157
- revoked_at_ms: expect.any(Number),
158
- });
159
- expect(revoked).not.toHaveProperty("hash");
160
- expect(beforeOperation).toHaveBeenCalledTimes(3);
161
- });
162
- });
package/src/apiKeys.ts DELETED
@@ -1,220 +0,0 @@
1
- import type { ApiKeyModel, ApiKeyRow } from "@hot-updater/plugin-core";
2
-
3
- export const API_KEY_HEADER_NAME = "x-api-key";
4
-
5
- const BASE64URL_32_PATTERN = /^[A-Za-z0-9_-]{43}$/u;
6
-
7
- const bytesToBase64Url = (bytes: Uint8Array): string => {
8
- let binary = "";
9
- for (const byte of bytes) binary += String.fromCharCode(byte);
10
- return btoa(binary)
11
- .replaceAll("+", "-")
12
- .replaceAll("/", "_")
13
- .replace(/=+$/u, "");
14
- };
15
-
16
- export const isApiKey = (value: string): boolean => {
17
- if (!BASE64URL_32_PATTERN.test(value)) return false;
18
-
19
- try {
20
- const base64 = value.replaceAll("-", "+").replaceAll("_", "/");
21
- const binary = atob(`${base64}=`);
22
- const bytes = Uint8Array.from(binary, (character) =>
23
- character.charCodeAt(0),
24
- );
25
- return bytes.byteLength === 32 && bytesToBase64Url(bytes) === value;
26
- } catch {
27
- return false;
28
- }
29
- };
30
-
31
- export const normalizeApiKeyHeaderName = (
32
- value: unknown = API_KEY_HEADER_NAME,
33
- ): string => {
34
- if (typeof value !== "string" || value.length === 0) {
35
- throw new TypeError("clientAccess.headerName must be a valid header name.");
36
- }
37
-
38
- try {
39
- const headers = new Headers();
40
- headers.set(value, "");
41
- return headers.keys().next().value!;
42
- } catch {
43
- throw new TypeError("clientAccess.headerName must be a valid header name.");
44
- }
45
- };
46
-
47
- export const hashApiKey = async (apiKey: string): Promise<string> => {
48
- if (!isApiKey(apiKey)) {
49
- throw new TypeError("API key must be a canonical 32-byte base64url value.");
50
- }
51
- const digest = await crypto.subtle.digest(
52
- "SHA-256",
53
- new TextEncoder().encode(apiKey),
54
- );
55
- return bytesToBase64Url(new Uint8Array(digest));
56
- };
57
-
58
- export const apiKeyId = (): string => {
59
- const bytes = new Uint8Array(16);
60
- crypto.getRandomValues(bytes);
61
- return `api-${bytesToBase64Url(bytes)}`;
62
- };
63
-
64
- export const normalizeApiKeyName = (name: string): string => {
65
- const normalized = name.trim();
66
- if (
67
- normalized.length === 0 ||
68
- normalized.length > 64 ||
69
- /[\p{Cc}\p{Cf}]/u.test(normalized)
70
- ) {
71
- throw new TypeError("API key names must contain 1-64 visible characters.");
72
- }
73
- return normalized;
74
- };
75
-
76
- export type ApiKeyMetadata = Omit<ApiKeyRow, "hash">;
77
-
78
- export interface CreatedApiKey {
79
- /** Plaintext credential. It cannot be recovered after this call returns. */
80
- readonly apiKey: string;
81
- /** Non-secret metadata. The persisted SHA-256 hash is never exposed. */
82
- readonly record: ApiKeyMetadata;
83
- }
84
-
85
- export interface ApiKeyManagementAPI {
86
- /** Creates an API key and returns its plaintext exactly once. */
87
- create(input: { readonly name: string }): Promise<{
88
- readonly apiKey: string;
89
- readonly record: ApiKeyMetadata;
90
- }>;
91
- /** Lists non-secret API key metadata, including revoked keys. */
92
- list(): Promise<readonly ApiKeyMetadata[]>;
93
- /** Revokes an API key immediately and returns only non-secret metadata. */
94
- revoke(input: { readonly id: string }): Promise<ApiKeyMetadata | null>;
95
- }
96
-
97
- const toApiKeyMetadata = ({
98
- hash: _hash,
99
- ...metadata
100
- }: ApiKeyRow): ApiKeyMetadata => Object.freeze(metadata);
101
-
102
- export const registerApiKey = async (input: {
103
- readonly apiKey: string;
104
- readonly apiKeys: ApiKeyModel;
105
- readonly createdAtMs?: number;
106
- readonly name: string;
107
- }): Promise<CreatedApiKey> => {
108
- const hash = await hashApiKey(input.apiKey);
109
- const createdAtMs = input.createdAtMs ?? Date.now();
110
- if (!Number.isSafeInteger(createdAtMs) || createdAtMs < 0) {
111
- throw new TypeError("API key creation time must be non-negative.");
112
- }
113
- const record = Object.freeze({
114
- created_at_ms: createdAtMs,
115
- hash,
116
- id: apiKeyId(),
117
- name: normalizeApiKeyName(input.name),
118
- prefix: input.apiKey.slice(0, 6),
119
- revoked_at_ms: null,
120
- role: "client" as const,
121
- });
122
- const status = await input.apiKeys.create(record);
123
- if (status === "existing") {
124
- const existing = await input.apiKeys.findByHash(hash);
125
- if (existing === null || existing.revoked_at_ms !== null) {
126
- throw new Error("The API key has been revoked.");
127
- }
128
- return Object.freeze({
129
- apiKey: input.apiKey,
130
- record: toApiKeyMetadata(existing),
131
- });
132
- }
133
- return Object.freeze({
134
- apiKey: input.apiKey,
135
- record: toApiKeyMetadata(record),
136
- });
137
- };
138
-
139
- export const createApiKey = (input: {
140
- readonly apiKeys: ApiKeyModel;
141
- readonly name: string;
142
- }): Promise<CreatedApiKey> => {
143
- const bytes = new Uint8Array(32);
144
- crypto.getRandomValues(bytes);
145
- return registerApiKey({
146
- apiKey: bytesToBase64Url(bytes),
147
- apiKeys: input.apiKeys,
148
- name: input.name,
149
- });
150
- };
151
-
152
- /**
153
- * Provisions the client API key used by managed init.
154
- *
155
- * A saved plaintext key is registered idempotently; otherwise a new key is
156
- * created. Callers must persist or display the returned plaintext because the
157
- * database stores only its hash.
158
- */
159
- export const provisionApiKey = (input: {
160
- readonly apiKeys: ApiKeyModel;
161
- readonly existingApiKey?: string;
162
- readonly name: string;
163
- }): Promise<CreatedApiKey> => {
164
- const existingApiKey = input.existingApiKey?.trim();
165
- return existingApiKey
166
- ? registerApiKey({
167
- apiKey: existingApiKey,
168
- apiKeys: input.apiKeys,
169
- name: input.name,
170
- })
171
- : createApiKey({ apiKeys: input.apiKeys, name: input.name });
172
- };
173
-
174
- export const authenticateApiKey = async (input: {
175
- readonly beforeLookup?: () => Promise<void>;
176
- readonly apiKeys: ApiKeyModel;
177
- readonly headerName?: string;
178
- readonly request: Request;
179
- }): Promise<boolean> => {
180
- const apiKey = input.request.headers.get(
181
- normalizeApiKeyHeaderName(input.headerName),
182
- );
183
- if (apiKey === null || !isApiKey(apiKey)) return false;
184
- const hash = await hashApiKey(apiKey);
185
- await input.beforeLookup?.();
186
- const record = await input.apiKeys.findByHash(hash);
187
- return (
188
- record !== null &&
189
- record.hash === hash &&
190
- record.role === "client" &&
191
- record.revoked_at_ms === null
192
- );
193
- };
194
-
195
- export const createApiKeyManagement = (input: {
196
- readonly apiKeys: ApiKeyModel;
197
- readonly beforeOperation: () => Promise<void>;
198
- }): ApiKeyManagementAPI =>
199
- Object.freeze({
200
- async create({ name }: { readonly name: string }) {
201
- await input.beforeOperation();
202
- const created = await createApiKey({ apiKeys: input.apiKeys, name });
203
- return Object.freeze({
204
- apiKey: created.apiKey,
205
- record: created.record,
206
- });
207
- },
208
- async list() {
209
- await input.beforeOperation();
210
- return Object.freeze((await input.apiKeys.list()).map(toApiKeyMetadata));
211
- },
212
- async revoke({ id }: { readonly id: string }) {
213
- await input.beforeOperation();
214
- const record = await input.apiKeys.revoke({
215
- id,
216
- revokedAtMs: Date.now(),
217
- });
218
- return record === null ? null : toApiKeyMetadata(record);
219
- },
220
- });
@@ -1,34 +0,0 @@
1
- import type { PaginationInfo, PaginationOptions } from "./types";
2
-
3
- /**
4
- * Calculate pagination information based on total count, limit, and offset
5
- */
6
- export function calculatePagination(
7
- total: number,
8
- options: PaginationOptions,
9
- ): PaginationInfo {
10
- const { limit, offset } = options;
11
-
12
- if (total === 0) {
13
- return {
14
- total: 0,
15
- hasNextPage: false,
16
- hasPreviousPage: false,
17
- currentPage: 1,
18
- totalPages: 0,
19
- };
20
- }
21
-
22
- const currentPage = Math.floor(offset / limit) + 1;
23
- const totalPages = Math.ceil(total / limit);
24
- const hasNextPage = offset + limit < total;
25
- const hasPreviousPage = offset > 0;
26
-
27
- return {
28
- total,
29
- hasNextPage,
30
- hasPreviousPage,
31
- currentPage,
32
- totalPages,
33
- };
34
- }
@@ -1,246 +0,0 @@
1
- import {
2
- assertStorageOperations,
3
- type InsightsModel,
4
- type StoragePlugin,
5
- } from "@hot-updater/plugin-core";
6
-
7
- import {
8
- authenticateApiKey,
9
- createApiKeyManagement,
10
- normalizeApiKeyHeaderName,
11
- } from "./apiKeys";
12
- import type { ApiKeyManagementAPI } from "./apiKeys";
13
- import { createDatabasePluginCore } from "./db/databasePluginCore";
14
- import { createSchemaReadinessChecker } from "./db/schemaReadiness";
15
- import {
16
- type DatabaseAdapterCapabilities,
17
- type DatabaseAPI,
18
- type DatabasePlugin,
19
- isDatabasePlugin,
20
- } from "./db/types";
21
- import { createHotUpdaterHandlers, type HotUpdaterHandlers } from "./handler";
22
- import { createInsightsProvider } from "./insights/provider";
23
- import type { InsightsProvider } from "./insights/types";
24
- import { createStorageAccess } from "./storageAccess";
25
-
26
- export type RuntimeHotUpdaterAPI = DatabaseAPI & {
27
- readonly handlers: HotUpdaterHandlers;
28
- readonly adapterName: string;
29
- /**
30
- * Built-in Insights provider. Client ingestion and admin query routes are
31
- * always mounted; React Native clients report lifecycle events by default
32
- * and can opt out with `HotUpdater.init({ insights: false })`.
33
- */
34
- readonly insights: InsightsProvider;
35
- /**
36
- * In-process API key lifecycle operations for trusted server tooling.
37
- * Creation returns the plaintext once; list and revoke expose only metadata.
38
- * This capability is never mounted on the client or admin HTTP handlers.
39
- */
40
- readonly apiKeys: ApiKeyManagementAPI;
41
- };
42
-
43
- export type HotUpdaterAPI = RuntimeHotUpdaterAPI;
44
-
45
- export type ClientAccessPolicy =
46
- | {
47
- /**
48
- * Leaves Release Catalog, artifact, and Insights ingestion routes
49
- * publicly accessible without a client credential.
50
- */
51
- readonly type: "public";
52
- }
53
- | {
54
- /**
55
- * Requires a key registered in `database.models.apiKeys` for
56
- * Release Catalog, artifact, and Insights ingestion requests.
57
- */
58
- readonly type: "api-key";
59
- /**
60
- * Request header containing the API key. Defaults to
61
- * `x-api-key`. Clients must send the same header; Release Catalog
62
- * responses include it in `Vary` to preserve cache isolation.
63
- */
64
- readonly headerName?: string;
65
- };
66
-
67
- export interface CreateHotUpdaterOptions {
68
- readonly database: DatabasePlugin;
69
- /**
70
- * Required client-route access policy. This choice is explicit so a server
71
- * cannot accidentally change between public and authenticated OTA access.
72
- * `/version`, storage downloads, and admin-handler routes are unaffected.
73
- */
74
- readonly clientAccess: ClientAccessPolicy;
75
- /** Storage implementations used to read provider-specific storage URIs. */
76
- readonly storage?: readonly StoragePlugin[];
77
- }
78
-
79
- const normalizeClientAccess = (
80
- value: unknown,
81
- ):
82
- | { readonly type: "public" }
83
- | {
84
- readonly type: "api-key";
85
- readonly headerName: string;
86
- } => {
87
- if (value === null || typeof value !== "object" || Array.isArray(value)) {
88
- throw new TypeError("clientAccess must be an object.");
89
- }
90
- const policy = value as {
91
- readonly headerName?: unknown;
92
- readonly type?: unknown;
93
- };
94
- if (policy.type === "public") return { type: "public" };
95
- if (policy.type === "api-key") {
96
- return {
97
- headerName: normalizeApiKeyHeaderName(policy.headerName),
98
- type: "api-key",
99
- };
100
- }
101
- throw new TypeError(
102
- 'clientAccess.type must be either "public" or "api-key".',
103
- );
104
- };
105
-
106
- type DatabasePluginCore = {
107
- readonly api: DatabaseAPI;
108
- readonly adapterName: string;
109
- readonly createMigrator: () => never;
110
- readonly generateSchema: () => never;
111
- };
112
-
113
- export const hotUpdaterCoreMetadata = Symbol.for(
114
- "@hot-updater/server/core-metadata",
115
- );
116
-
117
- export type HotUpdaterCoreMetadata = {
118
- readonly adapterCapabilities: DatabaseAdapterCapabilities;
119
- readonly core: DatabasePluginCore;
120
- };
121
-
122
- export type HotUpdaterCore = {
123
- readonly api: RuntimeHotUpdaterAPI;
124
- readonly adapterCapabilities: DatabaseAdapterCapabilities;
125
- readonly core: DatabasePluginCore;
126
- };
127
-
128
- export function getHotUpdaterCoreMetadata(
129
- hotUpdater: RuntimeHotUpdaterAPI,
130
- ): HotUpdaterCoreMetadata | undefined {
131
- return (
132
- hotUpdater as RuntimeHotUpdaterAPI & {
133
- readonly [hotUpdaterCoreMetadata]?: HotUpdaterCoreMetadata;
134
- }
135
- )[hotUpdaterCoreMetadata];
136
- }
137
-
138
- export function createHotUpdaterCore(
139
- options: CreateHotUpdaterOptions,
140
- ): HotUpdaterCore {
141
- for (const key of ["authorityId", "catalogId"]) {
142
- if (Object.hasOwn(options, key)) {
143
- throw new TypeError(
144
- `Remove ${key} from createHotUpdater options. Catalog identity is managed internally.`,
145
- );
146
- }
147
- }
148
- const database = options.database;
149
- const storagePlugins = (options.storage ?? []).map((storage) => {
150
- assertStorageOperations(storage, ["get", "getDownloadUrl"]);
151
- return storage;
152
- });
153
- const { downloadStorageObject, readStorageText, resolveFileUrl } =
154
- createStorageAccess(storagePlugins);
155
- const adapterCapabilities: DatabaseAdapterCapabilities = database;
156
-
157
- if (!isDatabasePlugin(database)) {
158
- throw new Error("@hot-updater/server only supports database plugins.");
159
- }
160
-
161
- const plugin: DatabasePlugin = database;
162
- const adapterName = adapterCapabilities.adapterName ?? plugin.name;
163
- const assertSchemaReady = createSchemaReadinessChecker(
164
- adapterName,
165
- adapterCapabilities.createMigrator,
166
- );
167
- const core = createDatabasePluginCore(plugin, resolveFileUrl, {
168
- beforeOperation: assertSchemaReady,
169
- readStorageText,
170
- });
171
- const clientAccess = normalizeClientAccess(options.clientAccess);
172
- const insightsModel: InsightsModel = {
173
- async record(input) {
174
- await assertSchemaReady();
175
- return plugin.models.insights.record(input);
176
- },
177
- async listEvents(input) {
178
- await assertSchemaReady();
179
- return plugin.models.insights.listEvents(input);
180
- },
181
- async findInstallations(input) {
182
- await assertSchemaReady();
183
- return plugin.models.insights.findInstallations(input);
184
- },
185
- async countInstallations(input) {
186
- await assertSchemaReady();
187
- return plugin.models.insights.countInstallations(input);
188
- },
189
- async countEvents(input) {
190
- await assertSchemaReady();
191
- return plugin.models.insights.countEvents(input);
192
- },
193
- };
194
- const insights = createInsightsProvider(insightsModel);
195
- const apiKeys = createApiKeyManagement({
196
- apiKeys: plugin.models.apiKeys,
197
- beforeOperation: assertSchemaReady,
198
- });
199
-
200
- const handlers = createHotUpdaterHandlers(
201
- core.api,
202
- insights,
203
- clientAccess.type === "api-key"
204
- ? {
205
- authenticate: (request) =>
206
- authenticateApiKey({
207
- apiKeys: plugin.models.apiKeys,
208
- beforeLookup: assertSchemaReady,
209
- headerName: clientAccess.headerName,
210
- request,
211
- }),
212
- headerName: clientAccess.headerName,
213
- }
214
- : undefined,
215
- downloadStorageObject,
216
- );
217
-
218
- const api: RuntimeHotUpdaterAPI = Object.assign(
219
- {
220
- adapterName: adapterCapabilities.adapterName ?? core.adapterName,
221
- insights,
222
- apiKeys,
223
- handlers,
224
- },
225
- core.api,
226
- );
227
- Object.defineProperty(api, hotUpdaterCoreMetadata, {
228
- enumerable: false,
229
- value: {
230
- adapterCapabilities,
231
- core,
232
- } satisfies HotUpdaterCoreMetadata,
233
- });
234
-
235
- return {
236
- api,
237
- adapterCapabilities,
238
- core,
239
- };
240
- }
241
-
242
- export function createHotUpdater(
243
- options: CreateHotUpdaterOptions,
244
- ): RuntimeHotUpdaterAPI {
245
- return createHotUpdaterCore(options).api;
246
- }