@hot-updater/server 0.36.7 → 1.0.0-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/databaseConstraintErrors.cjs +23 -0
- package/dist/adapters/databaseConstraintErrors.mjs +21 -0
- package/dist/adapters/databasePluginUtils.cjs +117 -0
- package/dist/adapters/databasePluginUtils.mjs +106 -0
- package/dist/adapters/drizzle.cjs +53 -176
- package/dist/adapters/drizzle.d.cts +6 -4
- package/dist/adapters/drizzle.d.mts +6 -4
- package/dist/adapters/drizzle.mjs +54 -177
- package/dist/adapters/drizzleCrud.cjs +250 -0
- package/dist/adapters/drizzleCrud.mjs +249 -0
- package/dist/adapters/drizzleLazyDB.cjs +84 -36
- package/dist/adapters/drizzleLazyDB.mjs +84 -36
- package/dist/adapters/drizzleQuery.cjs +68 -0
- package/dist/adapters/drizzleQuery.mjs +67 -0
- package/dist/adapters/kysely.cjs +18 -138
- package/dist/adapters/kysely.d.cts +3 -12
- package/dist/adapters/kysely.d.mts +3 -12
- package/dist/adapters/kysely.mjs +19 -139
- package/dist/adapters/kyselyCrud.cjs +254 -0
- package/dist/adapters/kyselyCrud.mjs +253 -0
- package/dist/adapters/kyselyQuery.cjs +56 -0
- package/dist/adapters/kyselyQuery.mjs +55 -0
- package/dist/adapters/mongodb.cjs +21 -174
- package/dist/adapters/mongodb.d.cts +3 -2
- package/dist/adapters/mongodb.d.mts +3 -2
- package/dist/adapters/mongodb.mjs +21 -174
- package/dist/adapters/mongodbCollections.cjs +36 -0
- package/dist/adapters/mongodbCollections.mjs +30 -0
- package/dist/adapters/mongodbQuery.cjs +77 -0
- package/dist/adapters/mongodbQuery.mjs +70 -0
- package/dist/adapters/mongodbReads.cjs +148 -0
- package/dist/adapters/mongodbReads.mjs +147 -0
- package/dist/adapters/mongodbWrites.cjs +134 -0
- package/dist/adapters/mongodbWrites.mjs +133 -0
- package/dist/adapters/prisma.cjs +205 -180
- package/dist/adapters/prisma.d.cts +3 -3
- package/dist/adapters/prisma.d.mts +3 -3
- package/dist/adapters/prisma.mjs +206 -181
- package/dist/adapters/prismaQuery.cjs +58 -0
- package/dist/adapters/prismaQuery.mjs +56 -0
- package/dist/adapters/prismaRows.cjs +198 -0
- package/dist/adapters/prismaRows.mjs +188 -0
- package/dist/analytics/bounded/activeOverview.cjs +87 -0
- package/dist/analytics/bounded/activeOverview.mjs +85 -0
- package/dist/analytics/bounded/installationSearch.cjs +42 -0
- package/dist/analytics/bounded/installationSearch.mjs +42 -0
- package/dist/analytics/bounded/persistence.cjs +39 -0
- package/dist/analytics/bounded/persistence.mjs +38 -0
- package/dist/analytics/bounded/provider.cjs +170 -0
- package/dist/analytics/bounded/provider.d.cts +7 -0
- package/dist/analytics/bounded/provider.d.mts +7 -0
- package/dist/analytics/bounded/provider.mjs +170 -0
- package/dist/analytics/bounded/scan.cjs +144 -0
- package/dist/analytics/bounded/scan.mjs +138 -0
- package/dist/analytics/domain.d.cts +121 -0
- package/dist/analytics/domain.d.mts +121 -0
- package/dist/analytics/errors.cjs +22 -0
- package/dist/analytics/errors.mjs +20 -0
- package/dist/analytics/eventInput.cjs +111 -0
- package/dist/analytics/eventInput.mjs +111 -0
- package/dist/analytics/persistence.d.cts +6 -0
- package/dist/analytics/persistence.d.mts +6 -0
- package/dist/analytics/queryInput.cjs +58 -0
- package/dist/analytics/queryInput.mjs +55 -0
- package/dist/analytics/routes.cjs +63 -0
- package/dist/analytics/routes.mjs +61 -0
- package/dist/analytics/types.d.cts +17 -0
- package/dist/analytics/types.d.mts +17 -0
- package/dist/apiKeys.cjs +139 -0
- package/dist/apiKeys.d.cts +50 -0
- package/dist/apiKeys.d.mts +50 -0
- package/dist/apiKeys.mjs +133 -0
- package/dist/createHotUpdaterCore.cjs +48 -26
- package/dist/createHotUpdaterCore.d.cts +49 -17
- package/dist/createHotUpdaterCore.d.mts +49 -17
- package/dist/createHotUpdaterCore.mjs +51 -29
- package/dist/db/createBundleDiff.cjs +45 -68
- package/dist/db/createBundleDiff.d.cts +3 -3
- package/dist/db/createBundleDiff.d.mts +3 -3
- package/dist/db/createBundleDiff.mjs +47 -68
- package/dist/db/databasePluginCore.cjs +138 -0
- package/dist/db/databasePluginCore.mjs +137 -0
- package/dist/db/fixedMigrator.cjs +36 -93
- package/dist/db/fixedMigrator.mjs +36 -93
- package/dist/db/fixedMigratorMongo.cjs +319 -0
- package/dist/db/fixedMigratorMongo.mjs +319 -0
- package/dist/db/fixedMigratorShared.cjs +23 -0
- package/dist/db/fixedMigratorShared.mjs +18 -0
- package/dist/db/mongoMigrationExecution.cjs +11 -0
- package/dist/db/mongoMigrationExecution.mjs +11 -0
- package/dist/db/releaseCatalog.cjs +66 -0
- package/dist/db/releaseCatalog.d.cts +17 -0
- package/dist/db/releaseCatalog.d.mts +17 -0
- package/dist/db/releaseCatalog.mjs +64 -0
- package/dist/db/schema/mongodb.cjs +14 -6
- package/dist/db/schema/mongodb.mjs +14 -6
- package/dist/db/schema/registry.cjs +0 -2
- package/dist/db/schema/registry.mjs +1 -2
- package/dist/db/schema/sql.cjs +31 -14
- package/dist/db/schema/sql.mjs +32 -13
- package/dist/db/schema/sqlOperations.cjs +4 -4
- package/dist/db/schema/sqlOperations.mjs +5 -5
- package/dist/db/schemaGenerators.cjs +52 -18
- package/dist/db/schemaGenerators.mjs +52 -18
- package/dist/db/schemaReadiness.cjs +4 -3
- package/dist/db/schemaReadiness.mjs +4 -3
- package/dist/db/sqlMigrationExecution.cjs +67 -0
- package/dist/db/sqlMigrationExecution.mjs +66 -0
- package/dist/db/types.cjs +2 -6
- package/dist/db/types.d.cts +60 -16
- package/dist/db/types.d.mts +60 -16
- package/dist/db/types.mjs +3 -6
- package/dist/db/updateArtifacts.cjs +114 -60
- package/dist/db/updateArtifacts.mjs +117 -62
- package/dist/handler.cjs +108 -282
- package/dist/handler.d.cts +3 -46
- package/dist/handler.d.mts +3 -46
- package/dist/handler.mjs +107 -281
- package/dist/handlerBundleRoutes.cjs +155 -0
- package/dist/handlerBundleRoutes.mjs +155 -0
- package/dist/handlerErrors.cjs +9 -0
- package/dist/handlerErrors.mjs +9 -0
- package/dist/handlerParameters.cjs +39 -0
- package/dist/handlerParameters.mjs +34 -0
- package/dist/handlerReleaseCatalogRoutes.cjs +111 -0
- package/dist/handlerReleaseCatalogRoutes.mjs +110 -0
- package/dist/handlerReleaseManagementRoutes.cjs +125 -0
- package/dist/handlerReleaseManagementRoutes.mjs +124 -0
- package/dist/handlerTypes.d.cts +63 -0
- package/dist/handlerTypes.d.mts +63 -0
- package/dist/handlerVersionRoutes.cjs +10 -0
- package/dist/handlerVersionRoutes.d.cts +4 -0
- package/dist/handlerVersionRoutes.d.mts +4 -0
- package/dist/handlerVersionRoutes.mjs +9 -0
- package/dist/index.cjs +10 -1
- package/dist/index.d.cts +9 -3
- package/dist/index.d.mts +9 -3
- package/dist/index.mjs +5 -2
- package/dist/node.cjs +19 -12
- package/dist/node.d.cts +15 -10
- package/dist/node.d.mts +15 -10
- package/dist/node.mjs +19 -13
- package/dist/package.cjs +1 -1
- package/dist/package.mjs +1 -1
- package/dist/schema/dsl.cjs +19 -2
- package/dist/schema/dsl.mjs +17 -3
- package/dist/schema/index.cjs +1 -8
- package/dist/schema/index.mjs +2 -8
- package/dist/schema/types.cjs +3 -1
- package/dist/schema/types.mjs +3 -2
- package/dist/schema/v1_0_0.cjs +364 -0
- package/dist/schema/v1_0_0.mjs +357 -0
- package/dist/storageAccess.cjs +69 -25
- package/dist/storageAccess.mjs +68 -25
- package/dist/types/index.d.cts +4 -3
- package/dist/types/index.d.mts +5 -4
- package/package.json +8 -7
- package/src/adapters/databaseConstraintErrors.ts +25 -0
- package/src/adapters/databasePluginTestDatabase.ts +106 -0
- package/src/adapters/databasePluginUtils.spec.ts +29 -0
- package/src/adapters/databasePluginUtils.ts +214 -0
- package/src/adapters/drizzle.spec.ts +208 -47
- package/src/adapters/drizzle.ts +106 -293
- package/src/adapters/drizzleCrud.ts +419 -0
- package/src/adapters/drizzleLazyDB.ts +206 -100
- package/src/adapters/drizzleQuery.ts +164 -0
- package/src/adapters/kysely.spec.ts +126 -88
- package/src/adapters/kysely.ts +76 -334
- package/src/adapters/kyselyCrud.ts +588 -0
- package/src/adapters/kyselyQuery.ts +128 -0
- package/src/adapters/mongodb.spec.ts +141 -0
- package/src/adapters/mongodb.ts +60 -288
- package/src/adapters/mongodbCollections.ts +62 -0
- package/src/adapters/mongodbQuery.ts +226 -0
- package/src/adapters/mongodbReads.ts +311 -0
- package/src/adapters/mongodbRows.spec.ts +64 -0
- package/src/adapters/mongodbRows.ts +118 -0
- package/src/adapters/mongodbTestClient.ts +342 -0
- package/src/adapters/mongodbTestFilter.ts +166 -0
- package/src/adapters/mongodbWrites.ts +260 -0
- package/src/adapters/prisma.spec.ts +196 -0
- package/src/adapters/prisma.ts +417 -292
- package/src/adapters/prismaQuery.ts +129 -0
- package/src/adapters/prismaRows.spec.ts +98 -0
- package/src/adapters/prismaRows.ts +301 -0
- package/src/adapters/prismaTestClient.ts +396 -0
- package/src/analytics/analytics.integration.spec.ts +144 -0
- package/src/analytics/bounded/activeOverview.spec.ts +189 -0
- package/src/analytics/bounded/activeOverview.ts +148 -0
- package/src/analytics/bounded/installationSearch.spec.ts +130 -0
- package/src/analytics/bounded/installationSearch.ts +69 -0
- package/src/analytics/bounded/persistence.ts +43 -0
- package/src/analytics/bounded/provider.spec.ts +219 -0
- package/src/analytics/bounded/provider.ts +229 -0
- package/src/analytics/bounded/scan.ts +235 -0
- package/src/analytics/domain.ts +139 -0
- package/src/analytics/errors.ts +18 -0
- package/src/analytics/eventInput.ts +168 -0
- package/src/analytics/persistence.ts +10 -0
- package/src/analytics/queryInput.ts +102 -0
- package/src/analytics/routes.ts +123 -0
- package/src/analytics/types.ts +44 -0
- package/src/apiKeys.integration.spec.ts +192 -0
- package/src/apiKeys.spec.ts +162 -0
- package/src/apiKeys.ts +220 -0
- package/src/createHotUpdaterCore.ts +164 -100
- package/src/db/bundleRows.spec.ts +164 -0
- package/src/db/bundleRows.ts +10 -140
- package/src/db/createBundleDiff.spec.ts +172 -127
- package/src/db/createBundleDiff.ts +91 -110
- package/src/db/databasePluginCore.spec.ts +62 -0
- package/src/db/databasePluginCore.testFixtures.ts +76 -0
- package/src/db/databasePluginCore.ts +185 -0
- package/src/db/databasePluginUpdateCheck.bench.ts +107 -0
- package/src/db/fixedMigrator.spec.ts +184 -42
- package/src/db/fixedMigrator.ts +64 -205
- package/src/db/fixedMigratorMongo.spec.ts +192 -0
- package/src/db/fixedMigratorMongo.ts +425 -0
- package/src/db/fixedMigratorShared.ts +36 -0
- package/src/db/hotUpdaterSchema.ts +0 -1
- package/src/db/index.spec.ts +333 -1025
- package/src/db/mongoMigrationExecution.ts +23 -0
- package/src/db/node-sqlite.d.ts +25 -0
- package/src/db/releaseCatalog.ts +148 -0
- package/src/db/schema/mongodb.ts +20 -6
- package/src/db/schema/sql.ts +52 -11
- package/src/db/schema/sqlOperations.ts +5 -4
- package/src/db/schemaGenerators.ts +107 -23
- package/src/db/schemaReadiness.ts +2 -1
- package/src/db/sqlMigrationExecution.spec.ts +65 -0
- package/src/db/sqlMigrationExecution.ts +108 -0
- package/src/db/types.spec.ts +55 -0
- package/src/db/types.ts +129 -65
- package/src/db/updateArtifacts.spec.ts +359 -0
- package/src/db/updateArtifacts.ts +290 -126
- package/src/handler-standalone.integration.spec.ts +401 -364
- package/src/handler.spec.ts +137 -582
- package/src/handler.testFixtures.ts +30 -0
- package/src/handler.ts +218 -616
- package/src/handlerAuth.integration.spec.ts +33 -0
- package/src/handlerBundleRoutes.ts +259 -0
- package/src/handlerErrors.ts +7 -0
- package/src/handlerManagement.spec.ts +262 -0
- package/src/handlerParameters.ts +105 -0
- package/src/handlerReleaseCatalogRoutes.ts +154 -0
- package/src/handlerReleaseManagementRoutes.ts +213 -0
- package/src/handlerTypes.ts +96 -0
- package/src/handlerVersionRoutes.ts +12 -0
- package/src/index.ts +22 -2
- package/src/node.spec.ts +79 -10
- package/src/node.ts +20 -17
- package/src/releaseCatalogRoutes.integration.spec.ts +238 -0
- package/src/runtime.spec.ts +126 -959
- package/src/runtime.testFixtures.ts +71 -0
- package/src/schema/dsl-all-versions.spec.ts +26 -17
- package/src/schema/dsl.ts +41 -2
- package/src/schema/index.ts +3 -9
- package/src/schema/types.ts +9 -3
- package/src/schema/v1_0_0.spec.ts +146 -0
- package/src/schema/v1_0_0.ts +465 -0
- package/src/storageAccess.spec.ts +127 -32
- package/src/storageAccess.ts +106 -55
- package/src/types/index.ts +2 -1
- package/dist/db/bundleRows.cjs +0 -82
- package/dist/db/bundleRows.d.cts +0 -33
- package/dist/db/bundleRows.d.mts +0 -33
- package/dist/db/bundleRows.mjs +0 -79
- package/dist/db/pluginCore.cjs +0 -242
- package/dist/db/pluginCore.mjs +0 -241
- package/dist/db/schema/sqlMigrations.cjs +0 -74
- package/dist/db/schema/sqlMigrations.mjs +0 -73
- package/dist/db/schemaEnhancements.cjs +0 -20
- package/dist/db/schemaEnhancements.mjs +0 -19
- package/dist/route.cjs +0 -7
- package/dist/route.mjs +0 -7
- package/dist/schema/v0_21_0.cjs +0 -38
- package/dist/schema/v0_21_0.mjs +0 -37
- package/dist/schema/v0_29_0.cjs +0 -45
- package/dist/schema/v0_29_0.mjs +0 -44
- package/dist/schema/v0_31_0.cjs +0 -82
- package/dist/schema/v0_31_0.mjs +0 -80
- package/src/db/pluginCore.spec.ts +0 -1095
- package/src/db/pluginCore.ts +0 -475
- package/src/db/pluginUpdateCheck.bench.ts +0 -254
- package/src/db/schema/sqlMigrations.ts +0 -219
- package/src/db/schemaEnhancements.ts +0 -55
- package/src/route.ts +0 -7
- package/src/schema/v0_21_0.ts +0 -52
- package/src/schema/v0_29_0.ts +0 -62
- package/src/schema/v0_31_0.spec.ts +0 -73
- package/src/schema/v0_31_0.ts +0 -120
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
const require_errors = require("./errors.cjs");
|
|
2
|
+
//#region src/analytics/queryInput.ts
|
|
3
|
+
const EVENT_LIST_BOUNDS = {
|
|
4
|
+
defaultValue: 50,
|
|
5
|
+
maximum: 100,
|
|
6
|
+
minimum: 1
|
|
7
|
+
};
|
|
8
|
+
const EVENT_LIST_OFFSET_BOUNDS = {
|
|
9
|
+
defaultValue: 0,
|
|
10
|
+
minimum: 0
|
|
11
|
+
};
|
|
12
|
+
const MAX_USER_ID_LENGTH = 1024;
|
|
13
|
+
function parseInteger(url, key, bounds) {
|
|
14
|
+
const value = url.searchParams.get(key);
|
|
15
|
+
if (value === null) return bounds.defaultValue;
|
|
16
|
+
const parsed = Number(value);
|
|
17
|
+
if (!Number.isSafeInteger(parsed) || parsed < bounds.minimum || bounds.maximum !== void 0 && parsed > bounds.maximum) throw new require_errors.AnalyticsBadRequestError(`Invalid '${key}' query parameter.`);
|
|
18
|
+
return parsed;
|
|
19
|
+
}
|
|
20
|
+
const parsePagination = (request) => {
|
|
21
|
+
const url = new URL(request.url);
|
|
22
|
+
return {
|
|
23
|
+
limit: parseInteger(url, "limit", EVENT_LIST_BOUNDS),
|
|
24
|
+
offset: parseInteger(url, "offset", EVENT_LIST_OFFSET_BOUNDS)
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
const parseAnalyticsQuery = (request) => {
|
|
28
|
+
const window = new URL(request.url).searchParams.get("window") ?? "24h";
|
|
29
|
+
if (window !== "24h" && window !== "7d" && window !== "30d" && window !== "all") throw new require_errors.AnalyticsBadRequestError("Invalid 'window' query parameter.");
|
|
30
|
+
return {
|
|
31
|
+
...parsePagination(request),
|
|
32
|
+
window
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
const parseActiveInstallationInput = (request) => {
|
|
36
|
+
const url = new URL(request.url);
|
|
37
|
+
const windows = url.searchParams.getAll("window");
|
|
38
|
+
if (windows.length > 1) throw new require_errors.AnalyticsBadRequestError("Duplicate 'window' query parameter.");
|
|
39
|
+
const window = windows[0] ?? "30d";
|
|
40
|
+
if (window !== "24h" && window !== "7d" && window !== "30d") throw new require_errors.AnalyticsBadRequestError("Invalid 'window' query parameter.");
|
|
41
|
+
const userIds = url.searchParams.getAll("userId");
|
|
42
|
+
if (userIds.length > 1) throw new require_errors.AnalyticsBadRequestError("Duplicate 'userId' query parameter.");
|
|
43
|
+
const userId = userIds[0];
|
|
44
|
+
if (userId !== void 0 && (userId.length === 0 || userId.length > MAX_USER_ID_LENGTH)) throw new require_errors.AnalyticsBadRequestError("Invalid 'userId' query parameter.");
|
|
45
|
+
return userId === void 0 ? { window } : {
|
|
46
|
+
window,
|
|
47
|
+
userId
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
const parseSearchInput = (request) => ({
|
|
51
|
+
...parsePagination(request),
|
|
52
|
+
query: new URL(request.url).searchParams.get("query")?.trim() ?? ""
|
|
53
|
+
});
|
|
54
|
+
//#endregion
|
|
55
|
+
exports.parseActiveInstallationInput = parseActiveInstallationInput;
|
|
56
|
+
exports.parseAnalyticsQuery = parseAnalyticsQuery;
|
|
57
|
+
exports.parsePagination = parsePagination;
|
|
58
|
+
exports.parseSearchInput = parseSearchInput;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { AnalyticsBadRequestError } from "./errors.mjs";
|
|
2
|
+
//#region src/analytics/queryInput.ts
|
|
3
|
+
const EVENT_LIST_BOUNDS = {
|
|
4
|
+
defaultValue: 50,
|
|
5
|
+
maximum: 100,
|
|
6
|
+
minimum: 1
|
|
7
|
+
};
|
|
8
|
+
const EVENT_LIST_OFFSET_BOUNDS = {
|
|
9
|
+
defaultValue: 0,
|
|
10
|
+
minimum: 0
|
|
11
|
+
};
|
|
12
|
+
const MAX_USER_ID_LENGTH = 1024;
|
|
13
|
+
function parseInteger(url, key, bounds) {
|
|
14
|
+
const value = url.searchParams.get(key);
|
|
15
|
+
if (value === null) return bounds.defaultValue;
|
|
16
|
+
const parsed = Number(value);
|
|
17
|
+
if (!Number.isSafeInteger(parsed) || parsed < bounds.minimum || bounds.maximum !== void 0 && parsed > bounds.maximum) throw new AnalyticsBadRequestError(`Invalid '${key}' query parameter.`);
|
|
18
|
+
return parsed;
|
|
19
|
+
}
|
|
20
|
+
const parsePagination = (request) => {
|
|
21
|
+
const url = new URL(request.url);
|
|
22
|
+
return {
|
|
23
|
+
limit: parseInteger(url, "limit", EVENT_LIST_BOUNDS),
|
|
24
|
+
offset: parseInteger(url, "offset", EVENT_LIST_OFFSET_BOUNDS)
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
const parseAnalyticsQuery = (request) => {
|
|
28
|
+
const window = new URL(request.url).searchParams.get("window") ?? "24h";
|
|
29
|
+
if (window !== "24h" && window !== "7d" && window !== "30d" && window !== "all") throw new AnalyticsBadRequestError("Invalid 'window' query parameter.");
|
|
30
|
+
return {
|
|
31
|
+
...parsePagination(request),
|
|
32
|
+
window
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
const parseActiveInstallationInput = (request) => {
|
|
36
|
+
const url = new URL(request.url);
|
|
37
|
+
const windows = url.searchParams.getAll("window");
|
|
38
|
+
if (windows.length > 1) throw new AnalyticsBadRequestError("Duplicate 'window' query parameter.");
|
|
39
|
+
const window = windows[0] ?? "30d";
|
|
40
|
+
if (window !== "24h" && window !== "7d" && window !== "30d") throw new AnalyticsBadRequestError("Invalid 'window' query parameter.");
|
|
41
|
+
const userIds = url.searchParams.getAll("userId");
|
|
42
|
+
if (userIds.length > 1) throw new AnalyticsBadRequestError("Duplicate 'userId' query parameter.");
|
|
43
|
+
const userId = userIds[0];
|
|
44
|
+
if (userId !== void 0 && (userId.length === 0 || userId.length > MAX_USER_ID_LENGTH)) throw new AnalyticsBadRequestError("Invalid 'userId' query parameter.");
|
|
45
|
+
return userId === void 0 ? { window } : {
|
|
46
|
+
window,
|
|
47
|
+
userId
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
const parseSearchInput = (request) => ({
|
|
51
|
+
...parsePagination(request),
|
|
52
|
+
query: new URL(request.url).searchParams.get("query")?.trim() ?? ""
|
|
53
|
+
});
|
|
54
|
+
//#endregion
|
|
55
|
+
export { parseActiveInstallationInput, parseAnalyticsQuery, parsePagination, parseSearchInput };
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
const require_errors = require("./errors.cjs");
|
|
2
|
+
const require_eventInput = require("./eventInput.cjs");
|
|
3
|
+
const require_queryInput = require("./queryInput.cjs");
|
|
4
|
+
//#region src/analytics/routes.ts
|
|
5
|
+
const json = (body, status) => Response.json(body, {
|
|
6
|
+
headers: { "cache-control": "private, no-store" },
|
|
7
|
+
status
|
|
8
|
+
});
|
|
9
|
+
const requireParam = (params, key) => {
|
|
10
|
+
const value = params[key];
|
|
11
|
+
if (value === void 0 || value.length === 0) throw new require_errors.AnalyticsBadRequestError(`Missing route parameter: ${key}`);
|
|
12
|
+
return value;
|
|
13
|
+
};
|
|
14
|
+
const run = async (operation) => {
|
|
15
|
+
try {
|
|
16
|
+
return await operation();
|
|
17
|
+
} catch (error) {
|
|
18
|
+
if (error instanceof require_errors.AnalyticsBadRequestError) return json({ error: error.message }, 400);
|
|
19
|
+
if (error instanceof require_errors.AnalyticsPayloadTooLargeError) return json({ error: error.message }, 413);
|
|
20
|
+
if (error instanceof require_errors.AnalyticsScanLimitExceededError) return json({ error: {
|
|
21
|
+
code: "ANALYTICS_SCAN_LIMIT_EXCEEDED",
|
|
22
|
+
limit: error.limit
|
|
23
|
+
} }, 503);
|
|
24
|
+
throw error;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
const query = (operation) => run(async () => json(await operation(), 200));
|
|
28
|
+
const createAnalyticsRouteHandlers = (provider) => ({
|
|
29
|
+
appendBundleEvent: async (_params, request) => run(async () => {
|
|
30
|
+
await provider.appendBundleEvent(await require_eventInput.parseBundleEventRequest(request));
|
|
31
|
+
return new Response(null, { status: 204 });
|
|
32
|
+
}),
|
|
33
|
+
getBundleEventSummary: (params) => query(() => provider.getBundleEventSummary(requireParam(params, "id"))),
|
|
34
|
+
getBundleEventAnalytics: (params, request) => query(() => {
|
|
35
|
+
const input = require_queryInput.parseAnalyticsQuery(request);
|
|
36
|
+
return provider.getBundleEventAnalytics(requireParam(params, "id"), input.window, input.limit, input.offset);
|
|
37
|
+
}),
|
|
38
|
+
getBundleEventOverview: () => query(() => provider.getBundleEventOverview()),
|
|
39
|
+
getActiveInstallationOverview: (_params, request) => query(() => provider.getActiveInstallationOverview(require_queryInput.parseActiveInstallationInput(request))),
|
|
40
|
+
searchInstallations: (_params, request) => query(() => {
|
|
41
|
+
const input = require_queryInput.parseSearchInput(request);
|
|
42
|
+
return provider.searchInstallations(input.query, input.limit, input.offset);
|
|
43
|
+
}),
|
|
44
|
+
getInstallationHistory: (params, request) => query(() => {
|
|
45
|
+
const input = require_queryInput.parsePagination(request);
|
|
46
|
+
return provider.getInstallationHistory(requireParam(params, "installId"), input.limit, input.offset);
|
|
47
|
+
})
|
|
48
|
+
});
|
|
49
|
+
const registerAnalyticsClientRoutes = (add) => {
|
|
50
|
+
add("POST", "/events", "appendBundleEvent");
|
|
51
|
+
};
|
|
52
|
+
const registerAnalyticsAdminRoutes = (add) => {
|
|
53
|
+
add("GET", "/bundles/:id/events/summary", "getBundleEventSummary");
|
|
54
|
+
add("GET", "/bundles/:id/events/analytics", "getBundleEventAnalytics");
|
|
55
|
+
add("GET", "/installations/overview", "getBundleEventOverview");
|
|
56
|
+
add("GET", "/installations/active", "getActiveInstallationOverview");
|
|
57
|
+
add("GET", "/installations", "searchInstallations");
|
|
58
|
+
add("GET", "/installations/:installId/events", "getInstallationHistory");
|
|
59
|
+
};
|
|
60
|
+
//#endregion
|
|
61
|
+
exports.createAnalyticsRouteHandlers = createAnalyticsRouteHandlers;
|
|
62
|
+
exports.registerAnalyticsAdminRoutes = registerAnalyticsAdminRoutes;
|
|
63
|
+
exports.registerAnalyticsClientRoutes = registerAnalyticsClientRoutes;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { AnalyticsBadRequestError, AnalyticsPayloadTooLargeError, AnalyticsScanLimitExceededError } from "./errors.mjs";
|
|
2
|
+
import { parseBundleEventRequest } from "./eventInput.mjs";
|
|
3
|
+
import { parseActiveInstallationInput, parseAnalyticsQuery, parsePagination, parseSearchInput } from "./queryInput.mjs";
|
|
4
|
+
//#region src/analytics/routes.ts
|
|
5
|
+
const json = (body, status) => Response.json(body, {
|
|
6
|
+
headers: { "cache-control": "private, no-store" },
|
|
7
|
+
status
|
|
8
|
+
});
|
|
9
|
+
const requireParam = (params, key) => {
|
|
10
|
+
const value = params[key];
|
|
11
|
+
if (value === void 0 || value.length === 0) throw new AnalyticsBadRequestError(`Missing route parameter: ${key}`);
|
|
12
|
+
return value;
|
|
13
|
+
};
|
|
14
|
+
const run = async (operation) => {
|
|
15
|
+
try {
|
|
16
|
+
return await operation();
|
|
17
|
+
} catch (error) {
|
|
18
|
+
if (error instanceof AnalyticsBadRequestError) return json({ error: error.message }, 400);
|
|
19
|
+
if (error instanceof AnalyticsPayloadTooLargeError) return json({ error: error.message }, 413);
|
|
20
|
+
if (error instanceof AnalyticsScanLimitExceededError) return json({ error: {
|
|
21
|
+
code: "ANALYTICS_SCAN_LIMIT_EXCEEDED",
|
|
22
|
+
limit: error.limit
|
|
23
|
+
} }, 503);
|
|
24
|
+
throw error;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
const query = (operation) => run(async () => json(await operation(), 200));
|
|
28
|
+
const createAnalyticsRouteHandlers = (provider) => ({
|
|
29
|
+
appendBundleEvent: async (_params, request) => run(async () => {
|
|
30
|
+
await provider.appendBundleEvent(await parseBundleEventRequest(request));
|
|
31
|
+
return new Response(null, { status: 204 });
|
|
32
|
+
}),
|
|
33
|
+
getBundleEventSummary: (params) => query(() => provider.getBundleEventSummary(requireParam(params, "id"))),
|
|
34
|
+
getBundleEventAnalytics: (params, request) => query(() => {
|
|
35
|
+
const input = parseAnalyticsQuery(request);
|
|
36
|
+
return provider.getBundleEventAnalytics(requireParam(params, "id"), input.window, input.limit, input.offset);
|
|
37
|
+
}),
|
|
38
|
+
getBundleEventOverview: () => query(() => provider.getBundleEventOverview()),
|
|
39
|
+
getActiveInstallationOverview: (_params, request) => query(() => provider.getActiveInstallationOverview(parseActiveInstallationInput(request))),
|
|
40
|
+
searchInstallations: (_params, request) => query(() => {
|
|
41
|
+
const input = parseSearchInput(request);
|
|
42
|
+
return provider.searchInstallations(input.query, input.limit, input.offset);
|
|
43
|
+
}),
|
|
44
|
+
getInstallationHistory: (params, request) => query(() => {
|
|
45
|
+
const input = parsePagination(request);
|
|
46
|
+
return provider.getInstallationHistory(requireParam(params, "installId"), input.limit, input.offset);
|
|
47
|
+
})
|
|
48
|
+
});
|
|
49
|
+
const registerAnalyticsClientRoutes = (add) => {
|
|
50
|
+
add("POST", "/events", "appendBundleEvent");
|
|
51
|
+
};
|
|
52
|
+
const registerAnalyticsAdminRoutes = (add) => {
|
|
53
|
+
add("GET", "/bundles/:id/events/summary", "getBundleEventSummary");
|
|
54
|
+
add("GET", "/bundles/:id/events/analytics", "getBundleEventAnalytics");
|
|
55
|
+
add("GET", "/installations/overview", "getBundleEventOverview");
|
|
56
|
+
add("GET", "/installations/active", "getActiveInstallationOverview");
|
|
57
|
+
add("GET", "/installations", "searchInstallations");
|
|
58
|
+
add("GET", "/installations/:installId/events", "getInstallationHistory");
|
|
59
|
+
};
|
|
60
|
+
//#endregion
|
|
61
|
+
export { createAnalyticsRouteHandlers, registerAnalyticsAdminRoutes, registerAnalyticsClientRoutes };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { ActiveInstallationInput, ActiveInstallationOverview, BundleEventAnalyticsResult, BundleEventAnalyticsWindow, BundleEventOverview, BundleEventSummary, BundleEventSummaryByBundle, CreateBundleEventRequest, InstallationHistoryRow, InstallationSearchRow, OffsetPaginationResult } from "./domain.cjs";
|
|
2
|
+
|
|
3
|
+
//#region src/analytics/types.d.ts
|
|
4
|
+
type AnalyticsProvider = {
|
|
5
|
+
readonly mode: "bounded";
|
|
6
|
+
readonly maxMatchingRows: number;
|
|
7
|
+
appendBundleEvent(input: CreateBundleEventRequest): Promise<void>;
|
|
8
|
+
getBundleEventSummary(bundleId: string): Promise<BundleEventSummary>;
|
|
9
|
+
getBundleEventSummaries(bundleIds: readonly string[], window: BundleEventAnalyticsWindow): Promise<readonly BundleEventSummaryByBundle[]>;
|
|
10
|
+
getBundleEventAnalytics(bundleId: string, window: BundleEventAnalyticsWindow, limit: number, offset: number): Promise<BundleEventAnalyticsResult>;
|
|
11
|
+
getBundleEventOverview(): Promise<BundleEventOverview>;
|
|
12
|
+
getActiveInstallationOverview(input: ActiveInstallationInput): Promise<ActiveInstallationOverview>;
|
|
13
|
+
searchInstallations(query: string, limit: number, offset: number): Promise<OffsetPaginationResult<InstallationSearchRow>>;
|
|
14
|
+
getInstallationHistory(installId: string, limit: number, offset: number): Promise<OffsetPaginationResult<InstallationHistoryRow>>;
|
|
15
|
+
};
|
|
16
|
+
//#endregion
|
|
17
|
+
export { AnalyticsProvider };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { ActiveInstallationInput, ActiveInstallationOverview, BundleEventAnalyticsResult, BundleEventAnalyticsWindow, BundleEventOverview, BundleEventSummary, BundleEventSummaryByBundle, CreateBundleEventRequest, InstallationHistoryRow, InstallationSearchRow, OffsetPaginationResult } from "./domain.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/analytics/types.d.ts
|
|
4
|
+
type AnalyticsProvider = {
|
|
5
|
+
readonly mode: "bounded";
|
|
6
|
+
readonly maxMatchingRows: number;
|
|
7
|
+
appendBundleEvent(input: CreateBundleEventRequest): Promise<void>;
|
|
8
|
+
getBundleEventSummary(bundleId: string): Promise<BundleEventSummary>;
|
|
9
|
+
getBundleEventSummaries(bundleIds: readonly string[], window: BundleEventAnalyticsWindow): Promise<readonly BundleEventSummaryByBundle[]>;
|
|
10
|
+
getBundleEventAnalytics(bundleId: string, window: BundleEventAnalyticsWindow, limit: number, offset: number): Promise<BundleEventAnalyticsResult>;
|
|
11
|
+
getBundleEventOverview(): Promise<BundleEventOverview>;
|
|
12
|
+
getActiveInstallationOverview(input: ActiveInstallationInput): Promise<ActiveInstallationOverview>;
|
|
13
|
+
searchInstallations(query: string, limit: number, offset: number): Promise<OffsetPaginationResult<InstallationSearchRow>>;
|
|
14
|
+
getInstallationHistory(installId: string, limit: number, offset: number): Promise<OffsetPaginationResult<InstallationHistoryRow>>;
|
|
15
|
+
};
|
|
16
|
+
//#endregion
|
|
17
|
+
export { AnalyticsProvider };
|
package/dist/apiKeys.cjs
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
//#region src/apiKeys.ts
|
|
2
|
+
const API_KEY_HEADER_NAME = "x-api-key";
|
|
3
|
+
const BASE64URL_32_PATTERN = /^[A-Za-z0-9_-]{43}$/u;
|
|
4
|
+
const bytesToBase64Url = (bytes) => {
|
|
5
|
+
let binary = "";
|
|
6
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
7
|
+
return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");
|
|
8
|
+
};
|
|
9
|
+
const isApiKey = (value) => {
|
|
10
|
+
if (!BASE64URL_32_PATTERN.test(value)) return false;
|
|
11
|
+
try {
|
|
12
|
+
const base64 = value.replaceAll("-", "+").replaceAll("_", "/");
|
|
13
|
+
const binary = atob(`${base64}=`);
|
|
14
|
+
const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
|
|
15
|
+
return bytes.byteLength === 32 && bytesToBase64Url(bytes) === value;
|
|
16
|
+
} catch {
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
const normalizeApiKeyHeaderName = (value = API_KEY_HEADER_NAME) => {
|
|
21
|
+
if (typeof value !== "string" || value.length === 0) throw new TypeError("clientAccess.headerName must be a valid header name.");
|
|
22
|
+
try {
|
|
23
|
+
const headers = new Headers();
|
|
24
|
+
headers.set(value, "");
|
|
25
|
+
return headers.keys().next().value;
|
|
26
|
+
} catch {
|
|
27
|
+
throw new TypeError("clientAccess.headerName must be a valid header name.");
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
const hashApiKey = async (apiKey) => {
|
|
31
|
+
if (!isApiKey(apiKey)) throw new TypeError("API key must be a canonical 32-byte base64url value.");
|
|
32
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(apiKey));
|
|
33
|
+
return bytesToBase64Url(new Uint8Array(digest));
|
|
34
|
+
};
|
|
35
|
+
const apiKeyId = () => {
|
|
36
|
+
const bytes = new Uint8Array(16);
|
|
37
|
+
crypto.getRandomValues(bytes);
|
|
38
|
+
return `api-${bytesToBase64Url(bytes)}`;
|
|
39
|
+
};
|
|
40
|
+
const normalizeApiKeyName = (name) => {
|
|
41
|
+
const normalized = name.trim();
|
|
42
|
+
if (normalized.length === 0 || normalized.length > 64 || /[\p{Cc}\p{Cf}]/u.test(normalized)) throw new TypeError("API key names must contain 1-64 visible characters.");
|
|
43
|
+
return normalized;
|
|
44
|
+
};
|
|
45
|
+
const toApiKeyMetadata = ({ hash: _hash, ...metadata }) => Object.freeze(metadata);
|
|
46
|
+
const registerApiKey = async (input) => {
|
|
47
|
+
const hash = await hashApiKey(input.apiKey);
|
|
48
|
+
const createdAtMs = input.createdAtMs ?? Date.now();
|
|
49
|
+
if (!Number.isSafeInteger(createdAtMs) || createdAtMs < 0) throw new TypeError("API key creation time must be non-negative.");
|
|
50
|
+
const record = Object.freeze({
|
|
51
|
+
created_at_ms: createdAtMs,
|
|
52
|
+
hash,
|
|
53
|
+
id: apiKeyId(),
|
|
54
|
+
name: normalizeApiKeyName(input.name),
|
|
55
|
+
prefix: input.apiKey.slice(0, 6),
|
|
56
|
+
revoked_at_ms: null,
|
|
57
|
+
role: "client"
|
|
58
|
+
});
|
|
59
|
+
if (await input.apiKeys.create(record) === "existing") {
|
|
60
|
+
const existing = await input.apiKeys.findByHash(hash);
|
|
61
|
+
if (existing === null || existing.revoked_at_ms !== null) throw new Error("The API key has been revoked.");
|
|
62
|
+
return Object.freeze({
|
|
63
|
+
apiKey: input.apiKey,
|
|
64
|
+
record: toApiKeyMetadata(existing)
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
return Object.freeze({
|
|
68
|
+
apiKey: input.apiKey,
|
|
69
|
+
record: toApiKeyMetadata(record)
|
|
70
|
+
});
|
|
71
|
+
};
|
|
72
|
+
const createApiKey = (input) => {
|
|
73
|
+
const bytes = new Uint8Array(32);
|
|
74
|
+
crypto.getRandomValues(bytes);
|
|
75
|
+
return registerApiKey({
|
|
76
|
+
apiKey: bytesToBase64Url(bytes),
|
|
77
|
+
apiKeys: input.apiKeys,
|
|
78
|
+
name: input.name
|
|
79
|
+
});
|
|
80
|
+
};
|
|
81
|
+
/**
|
|
82
|
+
* Provisions the client API key used by managed init.
|
|
83
|
+
*
|
|
84
|
+
* A saved plaintext key is registered idempotently; otherwise a new key is
|
|
85
|
+
* created. Callers must persist or display the returned plaintext because the
|
|
86
|
+
* database stores only its hash.
|
|
87
|
+
*/
|
|
88
|
+
const provisionApiKey = (input) => {
|
|
89
|
+
const existingApiKey = input.existingApiKey?.trim();
|
|
90
|
+
return existingApiKey ? registerApiKey({
|
|
91
|
+
apiKey: existingApiKey,
|
|
92
|
+
apiKeys: input.apiKeys,
|
|
93
|
+
name: input.name
|
|
94
|
+
}) : createApiKey({
|
|
95
|
+
apiKeys: input.apiKeys,
|
|
96
|
+
name: input.name
|
|
97
|
+
});
|
|
98
|
+
};
|
|
99
|
+
const authenticateApiKey = async (input) => {
|
|
100
|
+
const apiKey = input.request.headers.get(normalizeApiKeyHeaderName(input.headerName));
|
|
101
|
+
if (apiKey === null || !isApiKey(apiKey)) return false;
|
|
102
|
+
const hash = await hashApiKey(apiKey);
|
|
103
|
+
await input.beforeLookup?.();
|
|
104
|
+
const record = await input.apiKeys.findByHash(hash);
|
|
105
|
+
return record !== null && record.hash === hash && record.role === "client" && record.revoked_at_ms === null;
|
|
106
|
+
};
|
|
107
|
+
const createApiKeyManagement = (input) => Object.freeze({
|
|
108
|
+
async create({ name }) {
|
|
109
|
+
await input.beforeOperation();
|
|
110
|
+
const created = await createApiKey({
|
|
111
|
+
apiKeys: input.apiKeys,
|
|
112
|
+
name
|
|
113
|
+
});
|
|
114
|
+
return Object.freeze({
|
|
115
|
+
apiKey: created.apiKey,
|
|
116
|
+
record: created.record
|
|
117
|
+
});
|
|
118
|
+
},
|
|
119
|
+
async list() {
|
|
120
|
+
await input.beforeOperation();
|
|
121
|
+
return Object.freeze((await input.apiKeys.list()).map(toApiKeyMetadata));
|
|
122
|
+
},
|
|
123
|
+
async revoke({ id }) {
|
|
124
|
+
await input.beforeOperation();
|
|
125
|
+
const record = await input.apiKeys.revoke({
|
|
126
|
+
id,
|
|
127
|
+
revokedAtMs: Date.now()
|
|
128
|
+
});
|
|
129
|
+
return record === null ? null : toApiKeyMetadata(record);
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
//#endregion
|
|
133
|
+
exports.API_KEY_HEADER_NAME = API_KEY_HEADER_NAME;
|
|
134
|
+
exports.authenticateApiKey = authenticateApiKey;
|
|
135
|
+
exports.createApiKey = createApiKey;
|
|
136
|
+
exports.createApiKeyManagement = createApiKeyManagement;
|
|
137
|
+
exports.normalizeApiKeyHeaderName = normalizeApiKeyHeaderName;
|
|
138
|
+
exports.provisionApiKey = provisionApiKey;
|
|
139
|
+
exports.registerApiKey = registerApiKey;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { ApiKeyModel, ApiKeyRow } from "@hot-updater/plugin-core";
|
|
2
|
+
|
|
3
|
+
//#region src/apiKeys.d.ts
|
|
4
|
+
declare const API_KEY_HEADER_NAME = "x-api-key";
|
|
5
|
+
type ApiKeyMetadata = Omit<ApiKeyRow, "hash">;
|
|
6
|
+
interface CreatedApiKey {
|
|
7
|
+
/** Plaintext credential. It cannot be recovered after this call returns. */
|
|
8
|
+
readonly apiKey: string;
|
|
9
|
+
/** Non-secret metadata. The persisted SHA-256 hash is never exposed. */
|
|
10
|
+
readonly record: ApiKeyMetadata;
|
|
11
|
+
}
|
|
12
|
+
interface ApiKeyManagementAPI {
|
|
13
|
+
/** Creates an API key and returns its plaintext exactly once. */
|
|
14
|
+
create(input: {
|
|
15
|
+
readonly name: string;
|
|
16
|
+
}): Promise<{
|
|
17
|
+
readonly apiKey: string;
|
|
18
|
+
readonly record: ApiKeyMetadata;
|
|
19
|
+
}>;
|
|
20
|
+
/** Lists non-secret API key metadata, including revoked keys. */
|
|
21
|
+
list(): Promise<readonly ApiKeyMetadata[]>;
|
|
22
|
+
/** Revokes an API key immediately and returns only non-secret metadata. */
|
|
23
|
+
revoke(input: {
|
|
24
|
+
readonly id: string;
|
|
25
|
+
}): Promise<ApiKeyMetadata | null>;
|
|
26
|
+
}
|
|
27
|
+
declare const registerApiKey: (input: {
|
|
28
|
+
readonly apiKey: string;
|
|
29
|
+
readonly apiKeys: ApiKeyModel;
|
|
30
|
+
readonly createdAtMs?: number;
|
|
31
|
+
readonly name: string;
|
|
32
|
+
}) => Promise<CreatedApiKey>;
|
|
33
|
+
declare const createApiKey: (input: {
|
|
34
|
+
readonly apiKeys: ApiKeyModel;
|
|
35
|
+
readonly name: string;
|
|
36
|
+
}) => Promise<CreatedApiKey>;
|
|
37
|
+
/**
|
|
38
|
+
* Provisions the client API key used by managed init.
|
|
39
|
+
*
|
|
40
|
+
* A saved plaintext key is registered idempotently; otherwise a new key is
|
|
41
|
+
* created. Callers must persist or display the returned plaintext because the
|
|
42
|
+
* database stores only its hash.
|
|
43
|
+
*/
|
|
44
|
+
declare const provisionApiKey: (input: {
|
|
45
|
+
readonly apiKeys: ApiKeyModel;
|
|
46
|
+
readonly existingApiKey?: string;
|
|
47
|
+
readonly name: string;
|
|
48
|
+
}) => Promise<CreatedApiKey>;
|
|
49
|
+
//#endregion
|
|
50
|
+
export { API_KEY_HEADER_NAME, ApiKeyManagementAPI, ApiKeyMetadata, CreatedApiKey, createApiKey, provisionApiKey, registerApiKey };
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { ApiKeyModel, ApiKeyRow } from "@hot-updater/plugin-core";
|
|
2
|
+
|
|
3
|
+
//#region src/apiKeys.d.ts
|
|
4
|
+
declare const API_KEY_HEADER_NAME = "x-api-key";
|
|
5
|
+
type ApiKeyMetadata = Omit<ApiKeyRow, "hash">;
|
|
6
|
+
interface CreatedApiKey {
|
|
7
|
+
/** Plaintext credential. It cannot be recovered after this call returns. */
|
|
8
|
+
readonly apiKey: string;
|
|
9
|
+
/** Non-secret metadata. The persisted SHA-256 hash is never exposed. */
|
|
10
|
+
readonly record: ApiKeyMetadata;
|
|
11
|
+
}
|
|
12
|
+
interface ApiKeyManagementAPI {
|
|
13
|
+
/** Creates an API key and returns its plaintext exactly once. */
|
|
14
|
+
create(input: {
|
|
15
|
+
readonly name: string;
|
|
16
|
+
}): Promise<{
|
|
17
|
+
readonly apiKey: string;
|
|
18
|
+
readonly record: ApiKeyMetadata;
|
|
19
|
+
}>;
|
|
20
|
+
/** Lists non-secret API key metadata, including revoked keys. */
|
|
21
|
+
list(): Promise<readonly ApiKeyMetadata[]>;
|
|
22
|
+
/** Revokes an API key immediately and returns only non-secret metadata. */
|
|
23
|
+
revoke(input: {
|
|
24
|
+
readonly id: string;
|
|
25
|
+
}): Promise<ApiKeyMetadata | null>;
|
|
26
|
+
}
|
|
27
|
+
declare const registerApiKey: (input: {
|
|
28
|
+
readonly apiKey: string;
|
|
29
|
+
readonly apiKeys: ApiKeyModel;
|
|
30
|
+
readonly createdAtMs?: number;
|
|
31
|
+
readonly name: string;
|
|
32
|
+
}) => Promise<CreatedApiKey>;
|
|
33
|
+
declare const createApiKey: (input: {
|
|
34
|
+
readonly apiKeys: ApiKeyModel;
|
|
35
|
+
readonly name: string;
|
|
36
|
+
}) => Promise<CreatedApiKey>;
|
|
37
|
+
/**
|
|
38
|
+
* Provisions the client API key used by managed init.
|
|
39
|
+
*
|
|
40
|
+
* A saved plaintext key is registered idempotently; otherwise a new key is
|
|
41
|
+
* created. Callers must persist or display the returned plaintext because the
|
|
42
|
+
* database stores only its hash.
|
|
43
|
+
*/
|
|
44
|
+
declare const provisionApiKey: (input: {
|
|
45
|
+
readonly apiKeys: ApiKeyModel;
|
|
46
|
+
readonly existingApiKey?: string;
|
|
47
|
+
readonly name: string;
|
|
48
|
+
}) => Promise<CreatedApiKey>;
|
|
49
|
+
//#endregion
|
|
50
|
+
export { API_KEY_HEADER_NAME, ApiKeyManagementAPI, ApiKeyMetadata, CreatedApiKey, createApiKey, provisionApiKey, registerApiKey };
|
package/dist/apiKeys.mjs
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
//#region src/apiKeys.ts
|
|
2
|
+
const API_KEY_HEADER_NAME = "x-api-key";
|
|
3
|
+
const BASE64URL_32_PATTERN = /^[A-Za-z0-9_-]{43}$/u;
|
|
4
|
+
const bytesToBase64Url = (bytes) => {
|
|
5
|
+
let binary = "";
|
|
6
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
7
|
+
return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");
|
|
8
|
+
};
|
|
9
|
+
const isApiKey = (value) => {
|
|
10
|
+
if (!BASE64URL_32_PATTERN.test(value)) return false;
|
|
11
|
+
try {
|
|
12
|
+
const base64 = value.replaceAll("-", "+").replaceAll("_", "/");
|
|
13
|
+
const binary = atob(`${base64}=`);
|
|
14
|
+
const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
|
|
15
|
+
return bytes.byteLength === 32 && bytesToBase64Url(bytes) === value;
|
|
16
|
+
} catch {
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
const normalizeApiKeyHeaderName = (value = API_KEY_HEADER_NAME) => {
|
|
21
|
+
if (typeof value !== "string" || value.length === 0) throw new TypeError("clientAccess.headerName must be a valid header name.");
|
|
22
|
+
try {
|
|
23
|
+
const headers = new Headers();
|
|
24
|
+
headers.set(value, "");
|
|
25
|
+
return headers.keys().next().value;
|
|
26
|
+
} catch {
|
|
27
|
+
throw new TypeError("clientAccess.headerName must be a valid header name.");
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
const hashApiKey = async (apiKey) => {
|
|
31
|
+
if (!isApiKey(apiKey)) throw new TypeError("API key must be a canonical 32-byte base64url value.");
|
|
32
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(apiKey));
|
|
33
|
+
return bytesToBase64Url(new Uint8Array(digest));
|
|
34
|
+
};
|
|
35
|
+
const apiKeyId = () => {
|
|
36
|
+
const bytes = new Uint8Array(16);
|
|
37
|
+
crypto.getRandomValues(bytes);
|
|
38
|
+
return `api-${bytesToBase64Url(bytes)}`;
|
|
39
|
+
};
|
|
40
|
+
const normalizeApiKeyName = (name) => {
|
|
41
|
+
const normalized = name.trim();
|
|
42
|
+
if (normalized.length === 0 || normalized.length > 64 || /[\p{Cc}\p{Cf}]/u.test(normalized)) throw new TypeError("API key names must contain 1-64 visible characters.");
|
|
43
|
+
return normalized;
|
|
44
|
+
};
|
|
45
|
+
const toApiKeyMetadata = ({ hash: _hash, ...metadata }) => Object.freeze(metadata);
|
|
46
|
+
const registerApiKey = async (input) => {
|
|
47
|
+
const hash = await hashApiKey(input.apiKey);
|
|
48
|
+
const createdAtMs = input.createdAtMs ?? Date.now();
|
|
49
|
+
if (!Number.isSafeInteger(createdAtMs) || createdAtMs < 0) throw new TypeError("API key creation time must be non-negative.");
|
|
50
|
+
const record = Object.freeze({
|
|
51
|
+
created_at_ms: createdAtMs,
|
|
52
|
+
hash,
|
|
53
|
+
id: apiKeyId(),
|
|
54
|
+
name: normalizeApiKeyName(input.name),
|
|
55
|
+
prefix: input.apiKey.slice(0, 6),
|
|
56
|
+
revoked_at_ms: null,
|
|
57
|
+
role: "client"
|
|
58
|
+
});
|
|
59
|
+
if (await input.apiKeys.create(record) === "existing") {
|
|
60
|
+
const existing = await input.apiKeys.findByHash(hash);
|
|
61
|
+
if (existing === null || existing.revoked_at_ms !== null) throw new Error("The API key has been revoked.");
|
|
62
|
+
return Object.freeze({
|
|
63
|
+
apiKey: input.apiKey,
|
|
64
|
+
record: toApiKeyMetadata(existing)
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
return Object.freeze({
|
|
68
|
+
apiKey: input.apiKey,
|
|
69
|
+
record: toApiKeyMetadata(record)
|
|
70
|
+
});
|
|
71
|
+
};
|
|
72
|
+
const createApiKey = (input) => {
|
|
73
|
+
const bytes = new Uint8Array(32);
|
|
74
|
+
crypto.getRandomValues(bytes);
|
|
75
|
+
return registerApiKey({
|
|
76
|
+
apiKey: bytesToBase64Url(bytes),
|
|
77
|
+
apiKeys: input.apiKeys,
|
|
78
|
+
name: input.name
|
|
79
|
+
});
|
|
80
|
+
};
|
|
81
|
+
/**
|
|
82
|
+
* Provisions the client API key used by managed init.
|
|
83
|
+
*
|
|
84
|
+
* A saved plaintext key is registered idempotently; otherwise a new key is
|
|
85
|
+
* created. Callers must persist or display the returned plaintext because the
|
|
86
|
+
* database stores only its hash.
|
|
87
|
+
*/
|
|
88
|
+
const provisionApiKey = (input) => {
|
|
89
|
+
const existingApiKey = input.existingApiKey?.trim();
|
|
90
|
+
return existingApiKey ? registerApiKey({
|
|
91
|
+
apiKey: existingApiKey,
|
|
92
|
+
apiKeys: input.apiKeys,
|
|
93
|
+
name: input.name
|
|
94
|
+
}) : createApiKey({
|
|
95
|
+
apiKeys: input.apiKeys,
|
|
96
|
+
name: input.name
|
|
97
|
+
});
|
|
98
|
+
};
|
|
99
|
+
const authenticateApiKey = async (input) => {
|
|
100
|
+
const apiKey = input.request.headers.get(normalizeApiKeyHeaderName(input.headerName));
|
|
101
|
+
if (apiKey === null || !isApiKey(apiKey)) return false;
|
|
102
|
+
const hash = await hashApiKey(apiKey);
|
|
103
|
+
await input.beforeLookup?.();
|
|
104
|
+
const record = await input.apiKeys.findByHash(hash);
|
|
105
|
+
return record !== null && record.hash === hash && record.role === "client" && record.revoked_at_ms === null;
|
|
106
|
+
};
|
|
107
|
+
const createApiKeyManagement = (input) => Object.freeze({
|
|
108
|
+
async create({ name }) {
|
|
109
|
+
await input.beforeOperation();
|
|
110
|
+
const created = await createApiKey({
|
|
111
|
+
apiKeys: input.apiKeys,
|
|
112
|
+
name
|
|
113
|
+
});
|
|
114
|
+
return Object.freeze({
|
|
115
|
+
apiKey: created.apiKey,
|
|
116
|
+
record: created.record
|
|
117
|
+
});
|
|
118
|
+
},
|
|
119
|
+
async list() {
|
|
120
|
+
await input.beforeOperation();
|
|
121
|
+
return Object.freeze((await input.apiKeys.list()).map(toApiKeyMetadata));
|
|
122
|
+
},
|
|
123
|
+
async revoke({ id }) {
|
|
124
|
+
await input.beforeOperation();
|
|
125
|
+
const record = await input.apiKeys.revoke({
|
|
126
|
+
id,
|
|
127
|
+
revokedAtMs: Date.now()
|
|
128
|
+
});
|
|
129
|
+
return record === null ? null : toApiKeyMetadata(record);
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
//#endregion
|
|
133
|
+
export { API_KEY_HEADER_NAME, authenticateApiKey, createApiKey, createApiKeyManagement, normalizeApiKeyHeaderName, provisionApiKey, registerApiKey };
|