@degenerate/endpoints 0.1.6 → 0.2.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 (48) hide show
  1. package/dist/cors/authority/jwt/build-validate-jwt-for-audience.d.ts +41 -0
  2. package/dist/cors/authority/jwt/build-validate-jwt-for-audience.d.ts.map +1 -0
  3. package/dist/cors/authority/jwt/build-validate-jwt-for-audience.js +75 -0
  4. package/dist/cors/authority/jwt/validate-jwt-authorities.d.ts +5 -13
  5. package/dist/cors/authority/jwt/validate-jwt-authorities.d.ts.map +1 -1
  6. package/dist/cors/authority/jwt/validate-jwt-authorities.js +7 -27
  7. package/dist/cors/authority/jwt/validate-jwt-endpoints.d.ts +5 -13
  8. package/dist/cors/authority/jwt/validate-jwt-endpoints.d.ts.map +1 -1
  9. package/dist/cors/authority/jwt/validate-jwt-endpoints.js +7 -27
  10. package/dist/cors/authority/jwt/validate-jwt-events.d.ts +5 -13
  11. package/dist/cors/authority/jwt/validate-jwt-events.d.ts.map +1 -1
  12. package/dist/cors/authority/jwt/validate-jwt-events.js +7 -27
  13. package/dist/cors/authority/jwt/validate-jwt-functions.d.ts +5 -13
  14. package/dist/cors/authority/jwt/validate-jwt-functions.d.ts.map +1 -1
  15. package/dist/cors/authority/jwt/validate-jwt-functions.js +7 -27
  16. package/dist/cors/authority/jwt/validate-jwt-rules.d.ts +5 -13
  17. package/dist/cors/authority/jwt/validate-jwt-rules.d.ts.map +1 -1
  18. package/dist/cors/authority/jwt/validate-jwt-rules.js +7 -27
  19. package/dist/cors/authority/jwt/validate-jwt-share-data.d.ts +5 -13
  20. package/dist/cors/authority/jwt/validate-jwt-share-data.d.ts.map +1 -1
  21. package/dist/cors/authority/jwt/validate-jwt-share-data.js +7 -27
  22. package/dist/cors/endpoints/helpers/validate-incoming-request-data.d.ts.map +1 -1
  23. package/dist/cors/endpoints/helpers/validate-incoming-request-data.js +1 -1
  24. package/dist/cors/index.d.ts +1 -0
  25. package/dist/cors/index.d.ts.map +1 -1
  26. package/dist/cors/index.js +1 -0
  27. package/dist/examples/express-server/app.d.ts +20 -2
  28. package/dist/examples/express-server/app.d.ts.map +1 -1
  29. package/dist/examples/express-server/app.js +34 -21
  30. package/dist/examples/express-server/authenticate-realtime.d.ts +27 -0
  31. package/dist/examples/express-server/authenticate-realtime.d.ts.map +1 -0
  32. package/dist/examples/express-server/authenticate-realtime.js +23 -0
  33. package/dist/examples/express-server/server.d.ts +32 -1
  34. package/dist/examples/express-server/server.d.ts.map +1 -1
  35. package/dist/examples/express-server/server.js +61 -7
  36. package/dist/routes/events/v1.routes.d.ts +2 -0
  37. package/dist/routes/events/v1.routes.d.ts.map +1 -0
  38. package/dist/routes/events/v1.routes.js +87 -0
  39. package/dist/routes/functions/v1.routes.d.ts +2 -0
  40. package/dist/routes/functions/v1.routes.d.ts.map +1 -0
  41. package/dist/routes/functions/v1.routes.js +86 -0
  42. package/dist/routes/rules/v1/rule-set.routes.js +3 -3
  43. package/dist/routes/share-data.routes.d.ts.map +1 -1
  44. package/dist/routes/share-data.routes.js +17 -59
  45. package/dist/routes/sharedata/v1.routes.d.ts +2 -0
  46. package/dist/routes/sharedata/v1.routes.d.ts.map +1 -0
  47. package/dist/routes/sharedata/v1.routes.js +259 -0
  48. package/package.json +30 -14
@@ -0,0 +1,259 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.v1 = void 0;
37
+ const express = __importStar(require("express"));
38
+ const validate_jwt_share_data_1 = require("../../cors/authority/jwt/validate-jwt-share-data");
39
+ const add_unique_tracking_1 = require("../../cors/logging/add-unique-tracking");
40
+ const validate_request_body_1 = require("../../cors/endpoints/helpers/validate-request-body");
41
+ const validate_incoming_request_data_1 = require("../../cors/endpoints/helpers/validate-incoming-request-data");
42
+ const all_error_handler_1 = require("../../cors/errors/all-error-handler");
43
+ const bad_request_handler_1 = require("../../cors/errors/bad-request-handler");
44
+ const unauthorized_handler_1 = require("../../cors/errors/unauthorized-handler");
45
+ const generic_1 = require("@degenerate/generic");
46
+ const shareblock_1 = require("@degenerate/shareblock");
47
+ // eslint-disable-next-line new-cap
48
+ const router = express.Router({ mergeParams: true });
49
+ // The ShareDataManager is provided by the host application via
50
+ // `app.set('shareDataManager', manager)`. Sharing the same instance across
51
+ // HTTP and realtime is what makes route mutations broadcast to subscribed
52
+ // WebSocket clients. Tests must `app.set('shareDataManager', new ShareDataManager())`
53
+ // in their setup before mounting this router.
54
+ const getManager = (req) => {
55
+ const manager = req.app.get('shareDataManager');
56
+ if (!manager) {
57
+ throw new Error('shareDataManager is not registered on the app — see createApp()');
58
+ }
59
+ return manager;
60
+ };
61
+ // Authorization claims ride on the verified JWT as loosely-typed custom
62
+ // claims. Treat `allowedSigningKeys` as authoritative only when it is
63
+ // genuinely an array of strings — a malformed token that supplied a bare
64
+ // string would otherwise fall into String.prototype.includes substring
65
+ // semantics and could wrongly authorize a partially-matching key. Both the
66
+ // create and delete gates parse through here so they can't drift.
67
+ const getAllowedSigningKeys = (req) => {
68
+ const raw = req.auth?.customClaims?.allowedSigningKeys;
69
+ return Array.isArray(raw) && raw.every((k) => typeof k === 'string')
70
+ ? raw
71
+ : undefined;
72
+ };
73
+ router.use(add_unique_tracking_1.addUniqueTracking); // add the unique tracking id to the request
74
+ router.use(validate_jwt_share_data_1.validateJWTShareData); // validate the JWT token
75
+ /**
76
+ * This creates a new sharedata object.
77
+ */
78
+ router.post(// https://{hostname}/sharedata/v1
79
+ '/', validate_request_body_1.validateRequestBody, // make sure this is a valid request body
80
+ (0, validate_incoming_request_data_1.validateIncomingRequestData)(generic_1.ISAFETransactionShareDataAddSchema), async (req, res) => {
81
+ try {
82
+ const { metadata, initialState, initialCrypto, proofs } = req.body.transaction.data;
83
+ const creationPublicKey = initialCrypto.publicKey;
84
+ // Cross-check: the verified JWT must authorize the caller to sign
85
+ // as `creationPublicKey`. Token issuers attach
86
+ // `customClaims.allowedSigningKeys: string[]` listing the public
87
+ // keys the subject is vouched for — without this check, anyone
88
+ // holding a valid SHAREDATA JWT could create a block attributed to
89
+ // any key (since they generate the proofs themselves with their
90
+ // own keypair). The shared validateJWTShareData middleware has
91
+ // already verified signature/issuer/audience/expiry; this gate
92
+ // closes the subject → signing-key binding.
93
+ const allowedSigningKeys = getAllowedSigningKeys(req);
94
+ if (!allowedSigningKeys || !allowedSigningKeys.includes(creationPublicKey)) {
95
+ return res.status(403).send({
96
+ successful: false,
97
+ error: `creation-public-key-mismatch: JWT does not authorize signing as ${creationPublicKey}`,
98
+ });
99
+ }
100
+ // Cross-check: every proof in the bundle must be signed by the same
101
+ // key the initialCrypto attributes the block to. A mismatch means
102
+ // the client either swapped a proof in or supplied a forged
103
+ // creationPublicKey — reject early with one clear error rather
104
+ // than letting it surface as a verifyStructuralProof failure inside
105
+ // the factory.
106
+ for (const [purpose, proof] of Object.entries(proofs)) {
107
+ if (proof.publicKey !== creationPublicKey) {
108
+ return res.status(400).send({
109
+ successful: false,
110
+ error: `proof-public-key-mismatch: proof for '${purpose}' signed by ${proof.publicKey}, but initialCrypto attributes block to ${creationPublicKey}`,
111
+ });
112
+ }
113
+ }
114
+ // Cross-check: bundle covers every purpose the factory will request.
115
+ // Surfaces a missing proof once, here, instead of as the first
116
+ // MissingRequiredProofError thrown mid-construction.
117
+ const requiredPurposes = REQUIRED_PURPOSES_BY_BLOCK_TYPE[metadata.blockType];
118
+ for (const purpose of requiredPurposes) {
119
+ if (!(purpose in proofs)) {
120
+ return res.status(400).send({
121
+ successful: false,
122
+ error: `missing-proof: bundle is missing required proof for purpose '${purpose}' on ${metadata.blockType} ShareBlock`,
123
+ });
124
+ }
125
+ }
126
+ // Schema's literal union and the enum are the same string values —
127
+ // narrow once and reuse so we don't repeat the cast.
128
+ const blockType = metadata.blockType;
129
+ const proofFor = (0, shareblock_1.buildLookupProofFor)({
130
+ proofs,
131
+ initialCrypto,
132
+ blockType,
133
+ });
134
+ const factoryArgs = { metadata, creationPublicKey, initialState, proofFor };
135
+ let shareData;
136
+ switch (blockType) {
137
+ case generic_1.ShareBlockType.Clearing:
138
+ shareData = (0, shareblock_1.createClearingShareBlock)(factoryArgs);
139
+ break;
140
+ case generic_1.ShareBlockType.Funding:
141
+ shareData = (0, shareblock_1.createFundingShareBlock)(factoryArgs);
142
+ break;
143
+ case generic_1.ShareBlockType.Distribution:
144
+ shareData = (0, shareblock_1.createDistributionShareBlock)(factoryArgs);
145
+ break;
146
+ default: {
147
+ // Exhaustiveness check — schema validation should prevent
148
+ // reaching this, but TS doesn't know that. A runtime fallback
149
+ // makes the intent explicit and silences the unioned-undefined
150
+ // warning on `shareData`.
151
+ const _exhaustive = blockType;
152
+ return res.status(400).send({
153
+ successful: false,
154
+ error: `unknown blockType: ${_exhaustive}`,
155
+ });
156
+ }
157
+ }
158
+ // Carry the creation recipe so a repository-backed manager can persist
159
+ // this block and keep writing through as transactions accrue. The
160
+ // factory was handed exactly `{ metadata, creationPublicKey,
161
+ // initialState }`; the manager re-serializes from those.
162
+ await getManager(req).addShareData(shareData, {
163
+ blockType,
164
+ creationConfig: { metadata, creationPublicKey, initialState },
165
+ });
166
+ return res.status(200).send({ successful: true });
167
+ }
168
+ catch (error) {
169
+ const message = error instanceof Error ? error.message : 'Unknown error';
170
+ return res.status(400).send({ successful: false, error: message });
171
+ }
172
+ });
173
+ // Coverage-check table — keeps the per-variant required-proof list lookup
174
+ // in one place rather than hard-coding switches in the route body.
175
+ const REQUIRED_PURPOSES_BY_BLOCK_TYPE = {
176
+ [generic_1.ShareBlockType.Clearing]: shareblock_1.CLEARING_REQUIRED_PROOF_PURPOSES,
177
+ [generic_1.ShareBlockType.Funding]: shareblock_1.FUNDING_REQUIRED_PROOF_PURPOSES,
178
+ [generic_1.ShareBlockType.Distribution]: shareblock_1.DISTRIBUTION_REQUIRED_PROOF_PURPOSES,
179
+ };
180
+ /**
181
+ * This gets the sharedata objects and their data.
182
+ */
183
+ router.get(// https://{hostname}/sharedata/v1
184
+ '/', add_unique_tracking_1.addUniqueTracking, // add a unique tracking id to the request
185
+ async (req, res) => {
186
+ res.status(200).send({ successful: true });
187
+ return;
188
+ });
189
+ /**
190
+ * PATCH is intentionally unsupported. The previous handler replaced the
191
+ * stored ShareData wholesale with the request body — bypassing the rule
192
+ * engine and the structural-proof trust chain entirely. That is state
193
+ * forgery, not merely a missing access check: a caller could overwrite a
194
+ * block's canonical state with arbitrary JSON. In the SAFE model, state
195
+ * changes are signed PROPOSALS judged by `startRuleEvaluation` (the
196
+ * `ShareDataManager.applyTransaction` path), never client-uploaded blobs.
197
+ * Until a proposal-over-HTTP endpoint exists, PATCH stays closed. Body
198
+ * shape is still validated first, so malformed requests get 400 before 501.
199
+ */
200
+ router.patch(// https://{hostname}/sharedata/v1/{sharedataid}
201
+ '/:sharedataid', add_unique_tracking_1.addUniqueTracking, // add a unique tracking id to the request
202
+ validate_request_body_1.validateRequestBody, (0, validate_incoming_request_data_1.validateIncomingRequestData)(generic_1.ISAFETransactionShareDataUpdateSchema), async (_req, res) => {
203
+ return res.status(501).send({
204
+ successful: false,
205
+ error: 'patch-unsupported: ShareData mutations must go through the rule-engine-verified proposal path, not a wholesale state replacement.',
206
+ });
207
+ });
208
+ /**
209
+ * This deletes the sharedata object.
210
+ */
211
+ router.delete(// https://{hostname}/sharedata/v1/{sharedataid}
212
+ '/:sharedataid', add_unique_tracking_1.addUniqueTracking, // add a unique tracking id to the request
213
+ validate_request_body_1.validateRequestBody, (0, validate_incoming_request_data_1.validateIncomingRequestData)(generic_1.ISAFETransactionShareDataDeleteSchema), async (req, res) => {
214
+ try {
215
+ const shareDataId = req.params.sharedataid;
216
+ // Body/URL agreement: the wire payload names a target block; it must
217
+ // match the id in the URL path. A mismatch is a malformed request.
218
+ const bodyId = req.body
219
+ .transaction.data.metadata.shareBlockId;
220
+ if (bodyId !== shareDataId) {
221
+ return res.status(400).send({
222
+ successful: false,
223
+ error: `sharedata-id-mismatch: URL id ${shareDataId} does not match body id ${bodyId}`,
224
+ });
225
+ }
226
+ // Per-resource authorization (BOLA gate). The router-level
227
+ // validateJWTShareData only proves the caller holds a valid SHAREDATA
228
+ // token — it does NOT prove they may act on THIS block. Look up the
229
+ // target and require the verified JWT to vouch for the key that
230
+ // created it. Authorize against the stored block's creationPublicKey,
231
+ // never the client-supplied body. Mirrors the POST create gate.
232
+ const existing = getManager(req).getShareDataById(shareDataId);
233
+ if (!existing) {
234
+ return res.status(404).send({
235
+ successful: false,
236
+ error: `not-found: no ShareData with id ${shareDataId}`,
237
+ });
238
+ }
239
+ const allowedSigningKeys = getAllowedSigningKeys(req);
240
+ if (!allowedSigningKeys || !allowedSigningKeys.includes(existing.creationPublicKey)) {
241
+ return res.status(403).send({
242
+ successful: false,
243
+ error: `creation-public-key-mismatch: JWT does not authorize mutating block created by ${existing.creationPublicKey}`,
244
+ });
245
+ }
246
+ await getManager(req).removeShareDataById(shareDataId);
247
+ return res.status(200).send({ successful: true });
248
+ }
249
+ catch (error) {
250
+ const message = error instanceof Error ? error.message : 'Unknown error';
251
+ return res.status(400).send({ successful: false, error: message });
252
+ }
253
+ });
254
+ // Error handlers must be registered AFTER routes — express only routes
255
+ // errors to handlers that follow the throwing middleware in the chain.
256
+ router.use(unauthorized_handler_1.unauthorizedHandler); // the unauthorized handler should be the first error handler
257
+ router.use(bad_request_handler_1.badRequestHandler); // the bad request handler should be the second error handler
258
+ router.use(all_error_handler_1.allErrorHandler); // the all error handler catches all remaining errors
259
+ exports.v1 = router; // https://{hostname}/sharedata/v1
package/package.json CHANGED
@@ -1,21 +1,31 @@
1
1
  {
2
2
  "name": "@degenerate/endpoints",
3
- "version": "0.1.6",
3
+ "version": "0.2.0",
4
4
  "description": "This contains the ShareData Adaptive Framework Ecosystem (SAFE) network endpoint code",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ }
12
+ },
13
+ "publishConfig": {
14
+ "access": "public"
15
+ },
7
16
  "devDependencies": {
8
- "@types/jest": "^29.5.14",
9
- "@types/node": "^22.9.0",
10
- "jest": "^29.7.0",
11
- "ts-jest": "^29.2.5",
12
- "typescript": "^5.6.3"
17
+ "@types/express": "^5.0.6",
18
+ "@types/jest": "^30.0.0",
19
+ "@types/node": "^22.19.18",
20
+ "jest": "^30.4.2",
21
+ "ts-jest": "^29.4.9",
22
+ "typescript": "^6.0.3"
13
23
  },
14
24
  "scripts": {
15
25
  "build": "rm -rf dist/* && tsc -p tsconfig.pkg.json",
16
26
  "compile": "rm -rf dist/* && tsc -p tsconfig.pkg.json",
17
- "test": "jest --forceExit --detectOpenHandles --verbose --silent=false --env node --config tsconfig.pkg.json",
18
- "test:coverage": "jest --forceExit --coverage --detectOpenHandles --verbose --silent=false --env node --config tsconfig.pkg.json",
27
+ "test": "jest --forceExit --detectOpenHandles --verbose --silent=false --env node",
28
+ "test:coverage": "jest --forceExit --coverage --detectOpenHandles --verbose --silent=false --env node ",
19
29
  "test:clearCache": "jest --clearCache"
20
30
  },
21
31
  "repository": {
@@ -40,11 +50,17 @@
40
50
  "author": "Degenerate Inc.",
41
51
  "license": "ISC",
42
52
  "dependencies": {
43
- "@degenerate/generic": "^0.2.6",
44
- "@types/supertest": "^6.0.2",
45
- "express": "^4.21.1",
46
- "supertest": "^7.0.0",
47
- "zod": "^3.24.1"
53
+ "@degenerate/generic": "^0.3.0",
54
+ "@degenerate/realtime": "^0.1.0",
55
+ "@degenerate/shareblock": "^0.3.0",
56
+ "@degenerate/sharedata": "^0.3.0",
57
+ "@types/supertest": "^6.0.3",
58
+ "express": "^5.2.1",
59
+ "supertest": "^7.2.2",
60
+ "zod": "^4.4.3"
48
61
  },
49
- "gitHead": "a1ef457f3b707fb642b2e3296239c74bd75614b8"
62
+ "gitHead": "c33ed2f06679f5bd76c2eccf7054212c1820a014",
63
+ "engines": {
64
+ "node": ">=22"
65
+ }
50
66
  }