@pikku/core 0.12.3 → 0.12.4

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 (218) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/services/in-memory-workflow-service.d.ts +15 -2
  3. package/dist/services/in-memory-workflow-service.js +49 -0
  4. package/lcov.info +18891 -0
  5. package/package.json +1 -1
  6. package/src/crypto-utils.test.ts +0 -214
  7. package/src/crypto-utils.ts +0 -213
  8. package/src/errors/error-handler.ts +0 -62
  9. package/src/errors/error.test.ts +0 -195
  10. package/src/errors/errors.ts +0 -374
  11. package/src/errors/index.ts +0 -2
  12. package/src/factory-functions.test.ts +0 -109
  13. package/src/function/function-runner.test.ts +0 -536
  14. package/src/function/function-runner.ts +0 -365
  15. package/src/function/functions.types.ts +0 -304
  16. package/src/function/index.ts +0 -5
  17. package/src/handle-error.test.ts +0 -424
  18. package/src/handle-error.ts +0 -69
  19. package/src/index.ts +0 -118
  20. package/src/internal.ts +0 -6
  21. package/src/middleware/auth-apikey.test.ts +0 -363
  22. package/src/middleware/auth-apikey.ts +0 -47
  23. package/src/middleware/auth-bearer.test.ts +0 -450
  24. package/src/middleware/auth-bearer.ts +0 -72
  25. package/src/middleware/auth-cookie.test.ts +0 -528
  26. package/src/middleware/auth-cookie.ts +0 -80
  27. package/src/middleware/cors.test.ts +0 -424
  28. package/src/middleware/cors.ts +0 -104
  29. package/src/middleware/index.ts +0 -5
  30. package/src/middleware/remote-auth.test.ts +0 -488
  31. package/src/middleware/remote-auth.ts +0 -68
  32. package/src/middleware/timeout.ts +0 -15
  33. package/src/middleware-runner.test.ts +0 -418
  34. package/src/middleware-runner.ts +0 -234
  35. package/src/permissions.test.ts +0 -434
  36. package/src/permissions.ts +0 -319
  37. package/src/pikku-request.ts +0 -23
  38. package/src/pikku-response.ts +0 -5
  39. package/src/pikku-state.test.ts +0 -224
  40. package/src/pikku-state.ts +0 -216
  41. package/src/run-tests-script.test.ts +0 -49
  42. package/src/schema.test.ts +0 -249
  43. package/src/schema.ts +0 -151
  44. package/src/services/ai-agent-runner-service.ts +0 -41
  45. package/src/services/ai-run-state-service.ts +0 -20
  46. package/src/services/ai-storage-service.ts +0 -39
  47. package/src/services/content-service.ts +0 -76
  48. package/src/services/deployment-service.ts +0 -22
  49. package/src/services/gateway-service.ts +0 -20
  50. package/src/services/gopass-secrets.ts +0 -98
  51. package/src/services/in-memory-ai-run-state-service.ts +0 -73
  52. package/src/services/in-memory-trigger-service.ts +0 -64
  53. package/src/services/in-memory-workflow-service.test.ts +0 -351
  54. package/src/services/in-memory-workflow-service.ts +0 -438
  55. package/src/services/index.ts +0 -56
  56. package/src/services/jwt-service.ts +0 -30
  57. package/src/services/local-content.ts +0 -120
  58. package/src/services/local-gateway-service.ts +0 -62
  59. package/src/services/local-secrets.test.ts +0 -80
  60. package/src/services/local-secrets.ts +0 -94
  61. package/src/services/local-variables.test.ts +0 -61
  62. package/src/services/local-variables.ts +0 -39
  63. package/src/services/logger-console.test.ts +0 -118
  64. package/src/services/logger-console.ts +0 -98
  65. package/src/services/logger.ts +0 -57
  66. package/src/services/scheduler-service.ts +0 -86
  67. package/src/services/schema-service.ts +0 -33
  68. package/src/services/scoped-secret-service.test.ts +0 -74
  69. package/src/services/scoped-secret-service.ts +0 -41
  70. package/src/services/secret-service.ts +0 -38
  71. package/src/services/trigger-service.ts +0 -17
  72. package/src/services/typed-secret-service.test.ts +0 -93
  73. package/src/services/typed-secret-service.ts +0 -70
  74. package/src/services/typed-variables-service.test.ts +0 -73
  75. package/src/services/typed-variables-service.ts +0 -81
  76. package/src/services/user-session-service.test.ts +0 -113
  77. package/src/services/user-session-service.ts +0 -86
  78. package/src/services/variables-service.ts +0 -11
  79. package/src/services/workflow-service.ts +0 -95
  80. package/src/testing/index.ts +0 -2
  81. package/src/testing/service-tests.ts +0 -873
  82. package/src/time-utils.test.ts +0 -56
  83. package/src/time-utils.ts +0 -107
  84. package/src/types/core.types.ts +0 -478
  85. package/src/types/state.types.ts +0 -188
  86. package/src/utils/hash.test.ts +0 -68
  87. package/src/utils/hash.ts +0 -26
  88. package/src/utils.test.ts +0 -350
  89. package/src/utils.ts +0 -129
  90. package/src/version.test.ts +0 -80
  91. package/src/version.ts +0 -25
  92. package/src/wirings/ai-agent/agent-dynamic-workflow.ts +0 -469
  93. package/src/wirings/ai-agent/ai-agent-helpers.test.ts +0 -152
  94. package/src/wirings/ai-agent/ai-agent-helpers.ts +0 -76
  95. package/src/wirings/ai-agent/ai-agent-memory.ts +0 -310
  96. package/src/wirings/ai-agent/ai-agent-model-config.test.ts +0 -115
  97. package/src/wirings/ai-agent/ai-agent-model-config.ts +0 -43
  98. package/src/wirings/ai-agent/ai-agent-prepare.ts +0 -636
  99. package/src/wirings/ai-agent/ai-agent-registry.test.ts +0 -37
  100. package/src/wirings/ai-agent/ai-agent-registry.ts +0 -82
  101. package/src/wirings/ai-agent/ai-agent-runner.test.ts +0 -319
  102. package/src/wirings/ai-agent/ai-agent-runner.ts +0 -773
  103. package/src/wirings/ai-agent/ai-agent-stream.test.ts +0 -859
  104. package/src/wirings/ai-agent/ai-agent-stream.ts +0 -1153
  105. package/src/wirings/ai-agent/ai-agent.types.ts +0 -382
  106. package/src/wirings/ai-agent/index.ts +0 -37
  107. package/src/wirings/channel/channel-common.ts +0 -90
  108. package/src/wirings/channel/channel-handler.ts +0 -250
  109. package/src/wirings/channel/channel-middleware-runner.ts +0 -120
  110. package/src/wirings/channel/channel-runner.ts +0 -166
  111. package/src/wirings/channel/channel-store.ts +0 -29
  112. package/src/wirings/channel/channel.types.ts +0 -172
  113. package/src/wirings/channel/define-channel-routes.ts +0 -25
  114. package/src/wirings/channel/eventhub-service.ts +0 -34
  115. package/src/wirings/channel/eventhub-store.ts +0 -13
  116. package/src/wirings/channel/index.ts +0 -24
  117. package/src/wirings/channel/local/index.ts +0 -3
  118. package/src/wirings/channel/local/local-channel-handler.ts +0 -81
  119. package/src/wirings/channel/local/local-channel-runner.test.ts +0 -215
  120. package/src/wirings/channel/local/local-channel-runner.ts +0 -210
  121. package/src/wirings/channel/local/local-eventhub-service.test.ts +0 -95
  122. package/src/wirings/channel/local/local-eventhub-service.ts +0 -101
  123. package/src/wirings/channel/log-channels.ts +0 -20
  124. package/src/wirings/channel/pikku-abstract-channel-handler.test.ts +0 -54
  125. package/src/wirings/channel/pikku-abstract-channel-handler.ts +0 -45
  126. package/src/wirings/channel/serverless/index.ts +0 -5
  127. package/src/wirings/channel/serverless/serverless-channel-runner.ts +0 -289
  128. package/src/wirings/cli/channel/cli-channel-runner.ts +0 -136
  129. package/src/wirings/cli/channel/index.ts +0 -1
  130. package/src/wirings/cli/cli-runner.test.ts +0 -403
  131. package/src/wirings/cli/cli-runner.ts +0 -529
  132. package/src/wirings/cli/cli.types.ts +0 -358
  133. package/src/wirings/cli/command-parser.test.ts +0 -445
  134. package/src/wirings/cli/command-parser.ts +0 -504
  135. package/src/wirings/cli/define-cli-commands.ts +0 -24
  136. package/src/wirings/cli/index.ts +0 -19
  137. package/src/wirings/gateway/gateway-runner.test.ts +0 -474
  138. package/src/wirings/gateway/gateway-runner.ts +0 -411
  139. package/src/wirings/gateway/gateway.types.ts +0 -149
  140. package/src/wirings/gateway/index.ts +0 -13
  141. package/src/wirings/http/http-routes.test.ts +0 -322
  142. package/src/wirings/http/http-routes.ts +0 -197
  143. package/src/wirings/http/http-runner.test.ts +0 -144
  144. package/src/wirings/http/http-runner.ts +0 -588
  145. package/src/wirings/http/http.types.ts +0 -369
  146. package/src/wirings/http/index.ts +0 -28
  147. package/src/wirings/http/log-http-routes.ts +0 -22
  148. package/src/wirings/http/pikku-fetch-http-request.test.ts +0 -237
  149. package/src/wirings/http/pikku-fetch-http-request.ts +0 -170
  150. package/src/wirings/http/pikku-fetch-http-response.test.ts +0 -82
  151. package/src/wirings/http/pikku-fetch-http-response.ts +0 -147
  152. package/src/wirings/http/routers/http-router.ts +0 -13
  153. package/src/wirings/http/routers/path-to-regex.test.ts +0 -319
  154. package/src/wirings/http/routers/path-to-regex.ts +0 -126
  155. package/src/wirings/http/web-request.test.ts +0 -236
  156. package/src/wirings/http/web-request.ts +0 -104
  157. package/src/wirings/mcp/index.ts +0 -27
  158. package/src/wirings/mcp/mcp-endpoint-registry.test.ts +0 -389
  159. package/src/wirings/mcp/mcp-endpoint-registry.ts +0 -159
  160. package/src/wirings/mcp/mcp-runner.ts +0 -323
  161. package/src/wirings/mcp/mcp.types.ts +0 -216
  162. package/src/wirings/node/index.ts +0 -2
  163. package/src/wirings/node/node.types.ts +0 -23
  164. package/src/wirings/oauth2/index.ts +0 -3
  165. package/src/wirings/oauth2/oauth2-client.test.ts +0 -929
  166. package/src/wirings/oauth2/oauth2-client.ts +0 -335
  167. package/src/wirings/oauth2/oauth2.types.ts +0 -69
  168. package/src/wirings/oauth2/wire-oauth2-credential.ts +0 -23
  169. package/src/wirings/queue/index.ts +0 -31
  170. package/src/wirings/queue/queue-runner.test.ts +0 -710
  171. package/src/wirings/queue/queue-runner.ts +0 -192
  172. package/src/wirings/queue/queue.types.ts +0 -189
  173. package/src/wirings/queue/register-queue-helper.ts +0 -60
  174. package/src/wirings/queue/validate-worker-config.test.ts +0 -108
  175. package/src/wirings/queue/validate-worker-config.ts +0 -116
  176. package/src/wirings/rpc/index.ts +0 -4
  177. package/src/wirings/rpc/rpc-runner.ts +0 -460
  178. package/src/wirings/rpc/rpc-types.ts +0 -56
  179. package/src/wirings/rpc/wire-addon.ts +0 -21
  180. package/src/wirings/scheduler/index.ts +0 -11
  181. package/src/wirings/scheduler/log-schedulers.ts +0 -20
  182. package/src/wirings/scheduler/scheduler-runner.test.ts +0 -660
  183. package/src/wirings/scheduler/scheduler-runner.ts +0 -133
  184. package/src/wirings/scheduler/scheduler.types.ts +0 -53
  185. package/src/wirings/secret/index.ts +0 -9
  186. package/src/wirings/secret/secret.types.ts +0 -32
  187. package/src/wirings/secret/validate-secret-definitions.test.ts +0 -140
  188. package/src/wirings/secret/validate-secret-definitions.ts +0 -82
  189. package/src/wirings/trigger/index.ts +0 -10
  190. package/src/wirings/trigger/pikku-trigger-service.ts +0 -112
  191. package/src/wirings/trigger/trigger-runner.test.ts +0 -79
  192. package/src/wirings/trigger/trigger-runner.ts +0 -135
  193. package/src/wirings/trigger/trigger.types.ts +0 -178
  194. package/src/wirings/variable/index.ts +0 -8
  195. package/src/wirings/variable/validate-variable-definitions.test.ts +0 -91
  196. package/src/wirings/variable/validate-variable-definitions.ts +0 -69
  197. package/src/wirings/variable/variable.types.ts +0 -22
  198. package/src/wirings/workflow/dsl/index.ts +0 -31
  199. package/src/wirings/workflow/dsl/workflow-dsl.types.ts +0 -320
  200. package/src/wirings/workflow/dsl/workflow-runner.ts +0 -28
  201. package/src/wirings/workflow/graph/graph-node.ts +0 -222
  202. package/src/wirings/workflow/graph/graph-runner.test.ts +0 -487
  203. package/src/wirings/workflow/graph/graph-runner.ts +0 -816
  204. package/src/wirings/workflow/graph/graph-validation.test.ts +0 -170
  205. package/src/wirings/workflow/graph/graph-validation.ts +0 -237
  206. package/src/wirings/workflow/graph/index.ts +0 -19
  207. package/src/wirings/workflow/graph/template.test.ts +0 -49
  208. package/src/wirings/workflow/graph/template.ts +0 -42
  209. package/src/wirings/workflow/graph/wire-workflow-graph.ts +0 -29
  210. package/src/wirings/workflow/graph/workflow-graph.types.ts +0 -104
  211. package/src/wirings/workflow/index.ts +0 -82
  212. package/src/wirings/workflow/pikku-workflow-service.test.ts +0 -200
  213. package/src/wirings/workflow/pikku-workflow-service.ts +0 -1176
  214. package/src/wirings/workflow/workflow-helpers.test.ts +0 -129
  215. package/src/wirings/workflow/workflow-helpers.ts +0 -79
  216. package/src/wirings/workflow/workflow.types.ts +0 -274
  217. package/tsconfig.json +0 -14
  218. package/tsconfig.tsbuildinfo +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pikku/core",
3
- "version": "0.12.3",
3
+ "version": "0.12.4",
4
4
  "author": "yasser.fadl@gmail.com",
5
5
  "license": "MIT",
6
6
  "module": "dist/index.js",
@@ -1,214 +0,0 @@
1
- import { describe, test } from 'node:test'
2
- import assert from 'node:assert'
3
- import {
4
- encryptJSON,
5
- decryptJSON,
6
- generateDEK,
7
- wrapDEK,
8
- unwrapDEK,
9
- envelopeEncrypt,
10
- envelopeDecrypt,
11
- envelopeRewrap,
12
- } from './crypto-utils.js'
13
-
14
- describe('encryptJSON / decryptJSON', () => {
15
- const secret = 'test-secret-key-for-encryption'
16
-
17
- test('should round-trip a simple object', async () => {
18
- const original = { hello: 'world', num: 42 }
19
- const encrypted = await encryptJSON(secret, original)
20
- const decrypted = await decryptJSON(secret, encrypted)
21
- assert.deepStrictEqual(decrypted, original)
22
- })
23
-
24
- test('should round-trip a string value', async () => {
25
- const original = 'just a string'
26
- const encrypted = await encryptJSON(secret, original)
27
- const decrypted = await decryptJSON(secret, encrypted)
28
- assert.strictEqual(decrypted, original)
29
- })
30
-
31
- test('should round-trip a number', async () => {
32
- const original = 12345
33
- const encrypted = await encryptJSON(secret, original)
34
- const decrypted = await decryptJSON(secret, encrypted)
35
- assert.strictEqual(decrypted, original)
36
- })
37
-
38
- test('should round-trip null', async () => {
39
- const encrypted = await encryptJSON(secret, null)
40
- const decrypted = await decryptJSON(secret, encrypted)
41
- assert.strictEqual(decrypted, null)
42
- })
43
-
44
- test('should round-trip a boolean', async () => {
45
- const encrypted = await encryptJSON(secret, true)
46
- const decrypted = await decryptJSON(secret, encrypted)
47
- assert.strictEqual(decrypted, true)
48
- })
49
-
50
- test('should round-trip a nested object', async () => {
51
- const original = { user: { id: 1, roles: ['admin', 'user'] }, active: true }
52
- const encrypted = await encryptJSON(secret, original)
53
- const decrypted = await decryptJSON(secret, encrypted)
54
- assert.deepStrictEqual(decrypted, original)
55
- })
56
-
57
- test('should round-trip an array', async () => {
58
- const original = [1, 'two', { three: 3 }]
59
- const encrypted = await encryptJSON(secret, original)
60
- const decrypted = await decryptJSON(secret, encrypted)
61
- assert.deepStrictEqual(decrypted, original)
62
- })
63
-
64
- test('should produce different ciphertexts for same input (random IV)', async () => {
65
- const value = { same: 'data' }
66
- const enc1 = await encryptJSON(secret, value)
67
- const enc2 = await encryptJSON(secret, value)
68
- assert.notStrictEqual(enc1, enc2)
69
- })
70
-
71
- test('should produce a base64url string (no +, /, or = characters)', async () => {
72
- const encrypted = await encryptJSON(secret, { test: 'base64url' })
73
- assert.ok(!/[+/=]/.test(encrypted), `Expected base64url, got: ${encrypted}`)
74
- })
75
-
76
- test('should fail to decrypt with wrong secret', async () => {
77
- const encrypted = await encryptJSON(secret, { data: 'sensitive' })
78
- await assert.rejects(
79
- () => decryptJSON('wrong-secret', encrypted),
80
- (err: any) => err instanceof Error
81
- )
82
- })
83
-
84
- test('should reject an invalid encrypted payload (too short)', async () => {
85
- await assert.rejects(() => decryptJSON(secret, 'dG9vc2hvcnQ'), {
86
- message: 'Invalid encrypted payload',
87
- })
88
- })
89
-
90
- test('should reject empty string', async () => {
91
- await assert.rejects(() => decryptJSON(secret, ''), {
92
- message: 'Invalid encrypted payload',
93
- })
94
- })
95
-
96
- test('should reject corrupted ciphertext', async () => {
97
- const encrypted = await encryptJSON(secret, { data: 'test' })
98
- const corrupted = encrypted.slice(0, -4) + 'XXXX'
99
- await assert.rejects(
100
- () => decryptJSON(secret, corrupted),
101
- (err: any) => err instanceof Error
102
- )
103
- })
104
-
105
- test('should handle unicode content', async () => {
106
- const original = { emoji: '🎉', japanese: 'こんにちは', arabic: 'مرحبا' }
107
- const encrypted = await encryptJSON(secret, original)
108
- const decrypted = await decryptJSON(secret, encrypted)
109
- assert.deepStrictEqual(decrypted, original)
110
- })
111
-
112
- test('should handle empty object', async () => {
113
- const original = {}
114
- const encrypted = await encryptJSON(secret, original)
115
- const decrypted = await decryptJSON(secret, encrypted)
116
- assert.deepStrictEqual(decrypted, original)
117
- })
118
-
119
- test('should handle large payload', async () => {
120
- const original = { data: 'x'.repeat(10000) }
121
- const encrypted = await encryptJSON(secret, original)
122
- const decrypted = await decryptJSON(secret, encrypted)
123
- assert.deepStrictEqual(decrypted, original)
124
- })
125
- })
126
-
127
- describe('envelope encryption', () => {
128
- const kek = 'my-key-encryption-key'
129
-
130
- test('generateDEK produces unique keys', async () => {
131
- const dek1 = await generateDEK()
132
- const dek2 = await generateDEK()
133
- assert.notStrictEqual(dek1, dek2)
134
- assert.ok(dek1.length > 0)
135
- })
136
-
137
- test('wrapDEK / unwrapDEK round-trip', async () => {
138
- const dek = await generateDEK()
139
- const wrapped = await wrapDEK(kek, dek)
140
- const unwrapped = await unwrapDEK(kek, wrapped)
141
- assert.strictEqual(unwrapped, dek)
142
- })
143
-
144
- test('unwrapDEK fails with wrong KEK', async () => {
145
- const dek = await generateDEK()
146
- const wrapped = await wrapDEK(kek, dek)
147
- await assert.rejects(
148
- () => unwrapDEK('wrong-kek', wrapped),
149
- (err: any) => err instanceof Error
150
- )
151
- })
152
-
153
- test('envelopeEncrypt / envelopeDecrypt round-trip', async () => {
154
- const original = {
155
- apiKey: 'sk-secret-123',
156
- endpoint: 'https://api.example.com',
157
- }
158
- const { ciphertext, wrappedDEK } = await envelopeEncrypt(kek, original)
159
- const decrypted = await envelopeDecrypt(kek, ciphertext, wrappedDEK)
160
- assert.deepStrictEqual(decrypted, original)
161
- })
162
-
163
- test('envelopeEncrypt produces unique ciphertexts and DEKs per call', async () => {
164
- const value = { same: 'data' }
165
- const r1 = await envelopeEncrypt(kek, value)
166
- const r2 = await envelopeEncrypt(kek, value)
167
- assert.notStrictEqual(r1.ciphertext, r2.ciphertext)
168
- assert.notStrictEqual(r1.wrappedDEK, r2.wrappedDEK)
169
- })
170
-
171
- test('envelopeDecrypt fails with wrong KEK', async () => {
172
- const { ciphertext, wrappedDEK } = await envelopeEncrypt(kek, 'secret')
173
- await assert.rejects(
174
- () => envelopeDecrypt('wrong-kek', ciphertext, wrappedDEK),
175
- (err: any) => err instanceof Error
176
- )
177
- })
178
-
179
- test('envelopeRewrap allows decryption with new KEK', async () => {
180
- const newKEK = 'my-new-kek'
181
- const original = { token: 'abc-123' }
182
- const { ciphertext, wrappedDEK } = await envelopeEncrypt(kek, original)
183
-
184
- const rewrapped = await envelopeRewrap(kek, newKEK, wrappedDEK)
185
-
186
- await assert.rejects(
187
- () => envelopeDecrypt(kek, ciphertext, rewrapped),
188
- (err: any) => err instanceof Error
189
- )
190
-
191
- const decrypted = await envelopeDecrypt(newKEK, ciphertext, rewrapped)
192
- assert.deepStrictEqual(decrypted, original)
193
- })
194
-
195
- test('envelopeRewrap does not change the ciphertext', async () => {
196
- const original = { data: 'important' }
197
- const { ciphertext, wrappedDEK } = await envelopeEncrypt(kek, original)
198
- const rewrapped = await envelopeRewrap(kek, 'new-kek', wrappedDEK)
199
-
200
- assert.notStrictEqual(rewrapped, wrappedDEK)
201
-
202
- const decrypted = await envelopeDecrypt('new-kek', ciphertext, rewrapped)
203
- assert.deepStrictEqual(decrypted, original)
204
- })
205
-
206
- test('envelope handles string secrets', async () => {
207
- const { ciphertext, wrappedDEK } = await envelopeEncrypt(
208
- kek,
209
- 'plain-string-secret'
210
- )
211
- const decrypted = await envelopeDecrypt<string>(kek, ciphertext, wrappedDEK)
212
- assert.strictEqual(decrypted, 'plain-string-secret')
213
- })
214
- })
@@ -1,213 +0,0 @@
1
- const encoder = new TextEncoder()
2
- const decoder = new TextDecoder()
3
-
4
- const getSubtle = () => {
5
- const crypto = globalThis.crypto
6
- if (!crypto?.subtle) {
7
- throw new Error('WebCrypto not available')
8
- }
9
- return crypto.subtle
10
- }
11
-
12
- const base64Encode = (bytes: Uint8Array): string => {
13
- if (typeof Buffer !== 'undefined') {
14
- return Buffer.from(bytes).toString('base64')
15
- }
16
- let binary = ''
17
- for (let i = 0; i < bytes.length; i++) {
18
- binary += String.fromCharCode(bytes[i]!)
19
- }
20
- return btoa(binary)
21
- }
22
-
23
- const base64Decode = (input: string): Uint8Array => {
24
- if (typeof Buffer !== 'undefined') {
25
- return new Uint8Array(Buffer.from(input, 'base64'))
26
- }
27
- const binary = atob(input)
28
- const bytes = new Uint8Array(binary.length)
29
- for (let i = 0; i < binary.length; i++) {
30
- bytes[i] = binary.charCodeAt(i)
31
- }
32
- return bytes
33
- }
34
-
35
- const toBase64Url = (bytes: Uint8Array): string => {
36
- return base64Encode(bytes)
37
- .replace(/\+/g, '-')
38
- .replace(/\//g, '_')
39
- .replace(/=+$/g, '')
40
- }
41
-
42
- const fromBase64Url = (input: string): Uint8Array => {
43
- let base64 = input.replace(/-/g, '+').replace(/_/g, '/')
44
- while (base64.length % 4 !== 0) base64 += '='
45
- return base64Decode(base64)
46
- }
47
-
48
- const deriveKey = async (secret: string): Promise<CryptoKey> => {
49
- const subtle = getSubtle()
50
- const hash = await subtle.digest('SHA-256', encoder.encode(secret))
51
- return subtle.importKey('raw', hash, { name: 'AES-GCM' }, false, [
52
- 'encrypt',
53
- 'decrypt',
54
- ])
55
- }
56
-
57
- export const encryptJSON = async (
58
- secret: string,
59
- value: unknown
60
- ): Promise<string> => {
61
- const crypto = globalThis.crypto
62
- if (!crypto?.getRandomValues) {
63
- throw new Error('WebCrypto not available')
64
- }
65
- const subtle = getSubtle()
66
- const iv = crypto.getRandomValues(new Uint8Array(12))
67
- const key = await deriveKey(secret)
68
- const plaintext = encoder.encode(JSON.stringify(value))
69
- const encrypted = await subtle.encrypt(
70
- { name: 'AES-GCM', iv },
71
- key,
72
- plaintext
73
- )
74
- const cipherBytes = new Uint8Array(encrypted)
75
- const out = new Uint8Array(iv.length + cipherBytes.length)
76
- out.set(iv, 0)
77
- out.set(cipherBytes, iv.length)
78
- return toBase64Url(out)
79
- }
80
-
81
- export const decryptJSON = async <T>(
82
- secret: string,
83
- token: string
84
- ): Promise<T> => {
85
- const subtle = getSubtle()
86
- const data = fromBase64Url(token)
87
- if (data.length < 13) {
88
- throw new Error('Invalid encrypted payload')
89
- }
90
- const iv = data.slice(0, 12)
91
- const ciphertext = data.slice(12)
92
- const key = await deriveKey(secret)
93
- const decrypted = await subtle.decrypt(
94
- { name: 'AES-GCM', iv },
95
- key,
96
- ciphertext
97
- )
98
- return JSON.parse(decoder.decode(new Uint8Array(decrypted))) as T
99
- }
100
-
101
- /**
102
- * Envelope encryption utilities.
103
- *
104
- * Each secret gets its own random DEK (data encryption key).
105
- * The DEK is wrapped (encrypted) by a KEK (key encryption key) — typically an env var.
106
- * The actual secret is encrypted with the DEK.
107
- *
108
- * KEK rotation only re-wraps the DEK, never touches the ciphertext.
109
- */
110
-
111
- const importRawKey = async (rawBytes: Uint8Array): Promise<CryptoKey> => {
112
- const subtle = getSubtle()
113
- return subtle.importKey(
114
- 'raw',
115
- rawBytes.buffer as ArrayBuffer,
116
- { name: 'AES-GCM' },
117
- true,
118
- ['encrypt', 'decrypt']
119
- )
120
- }
121
-
122
- export const generateDEK = async (): Promise<string> => {
123
- const raw = globalThis.crypto.getRandomValues(new Uint8Array(32))
124
- return toBase64Url(raw)
125
- }
126
-
127
- export const wrapDEK = async (
128
- kek: string,
129
- plaintextDEK: string
130
- ): Promise<string> => {
131
- return encryptJSON(kek, plaintextDEK)
132
- }
133
-
134
- export const unwrapDEK = async (
135
- kek: string,
136
- wrappedDEK: string
137
- ): Promise<string> => {
138
- return decryptJSON<string>(kek, wrappedDEK)
139
- }
140
-
141
- const encryptWithDEK = async (
142
- dekBase64: string,
143
- value: unknown
144
- ): Promise<string> => {
145
- const crypto = globalThis.crypto
146
- const subtle = getSubtle()
147
- const iv = crypto.getRandomValues(new Uint8Array(12))
148
- const key = await importRawKey(fromBase64Url(dekBase64))
149
- const plaintext = encoder.encode(JSON.stringify(value))
150
- const encrypted = await subtle.encrypt(
151
- { name: 'AES-GCM', iv },
152
- key,
153
- plaintext
154
- )
155
- const cipherBytes = new Uint8Array(encrypted)
156
- const out = new Uint8Array(iv.length + cipherBytes.length)
157
- out.set(iv, 0)
158
- out.set(cipherBytes, iv.length)
159
- return toBase64Url(out)
160
- }
161
-
162
- const decryptWithDEK = async <T>(
163
- dekBase64: string,
164
- token: string
165
- ): Promise<T> => {
166
- const subtle = getSubtle()
167
- const data = fromBase64Url(token)
168
- if (data.length < 13) {
169
- throw new Error('Invalid encrypted payload')
170
- }
171
- const iv = data.slice(0, 12)
172
- const ciphertext = data.slice(12)
173
- const key = await importRawKey(fromBase64Url(dekBase64))
174
- const decrypted = await subtle.decrypt(
175
- { name: 'AES-GCM', iv },
176
- key,
177
- ciphertext
178
- )
179
- return JSON.parse(decoder.decode(new Uint8Array(decrypted))) as T
180
- }
181
-
182
- export interface EnvelopeEncryptResult {
183
- ciphertext: string
184
- wrappedDEK: string
185
- }
186
-
187
- export const envelopeEncrypt = async (
188
- kek: string,
189
- value: unknown
190
- ): Promise<EnvelopeEncryptResult> => {
191
- const dek = await generateDEK()
192
- const ciphertext = await encryptWithDEK(dek, value)
193
- const wrappedDEK = await wrapDEK(kek, dek)
194
- return { ciphertext, wrappedDEK }
195
- }
196
-
197
- export const envelopeDecrypt = async <T>(
198
- kek: string,
199
- ciphertext: string,
200
- wrappedDEK: string
201
- ): Promise<T> => {
202
- const dek = await unwrapDEK(kek, wrappedDEK)
203
- return decryptWithDEK<T>(dek, ciphertext)
204
- }
205
-
206
- export const envelopeRewrap = async (
207
- oldKEK: string,
208
- newKEK: string,
209
- wrappedDEK: string
210
- ): Promise<string> => {
211
- const dek = await unwrapDEK(oldKEK, wrappedDEK)
212
- return wrapDEK(newKEK, dek)
213
- }
@@ -1,62 +0,0 @@
1
- import { pikkuState } from '../pikku-state.js'
2
-
3
- /**
4
- * Base class for custom errors.
5
- * @extends {Error}
6
- */
7
- export class PikkuError extends Error {
8
- /**
9
- * Creates an instance of PikkuError.
10
- * @param message - The error message.
11
- */
12
- constructor(message: string = 'An error occurred') {
13
- super(message)
14
- Object.setPrototypeOf(this, new.target.prototype)
15
- }
16
- }
17
-
18
- /**
19
- * Interface for error details.
20
- */
21
- export interface ErrorDetails {
22
- status: number
23
- message: string
24
- mcpCode?: number
25
- }
26
-
27
- /**
28
- * Adds an error to the API errors map.
29
- * @param error - The error to add.
30
- * @param details - The details of the error.
31
- */
32
- export const addError = (error: any, { status, message }: ErrorDetails) => {
33
- pikkuState(null, 'misc', 'errors').set(error, { status, message })
34
- }
35
-
36
- /**
37
- * Adds multiple errors to the API errors map.
38
- * @param errors - An array of errors and their details.
39
- */
40
- export const addErrors = (
41
- errors: Array<[error: any, details: ErrorDetails]>
42
- ) => {
43
- errors.forEach((error) => {
44
- addError(error[0], error[1])
45
- })
46
- }
47
-
48
- /**
49
- * Retrieves the error response for a given error.
50
- * @param error - The error to get the response for.
51
- * @returns An object containing the status and message, or undefined if the error is not found.
52
- */
53
- export const getErrorResponse = (
54
- error: Error
55
- ): { status: number; message: string; mcpCode?: number } | undefined => {
56
- const errors = Array.from(pikkuState(null, 'misc', 'errors').entries())
57
- const foundError = errors.find(([e]) => e.name === error.constructor.name)
58
- if (foundError) {
59
- return foundError[1]
60
- }
61
- return pikkuState(null, 'misc', 'errors').get(error)
62
- }
@@ -1,195 +0,0 @@
1
- import { test, describe } from 'node:test'
2
- import assert from 'assert'
3
- import {
4
- getErrorResponse,
5
- addError,
6
- addErrors,
7
- PikkuError,
8
- } from './error-handler.js'
9
- import {
10
- BadRequestError,
11
- UnauthorizedError,
12
- MissingSessionError,
13
- InvalidSessionError,
14
- PaymentRequiredError,
15
- ForbiddenError,
16
- InvalidOriginError,
17
- NotFoundError,
18
- MethodNotAllowedError,
19
- NotAcceptableError,
20
- ProxyAuthenticationRequiredError,
21
- RequestTimeoutError,
22
- ConflictError,
23
- GoneError,
24
- LengthRequiredError,
25
- PreconditionFailedError,
26
- PayloadTooLargeError,
27
- URITooLongError,
28
- UnsupportedMediaTypeError,
29
- RangeNotSatisfiableError,
30
- ExpectationFailedError,
31
- UnprocessableContentError,
32
- LockedError,
33
- TooManyRequestsError,
34
- InternalServerError,
35
- NotImplementedError,
36
- BadGatewayError,
37
- ServiceUnavailableError,
38
- GatewayTimeoutError,
39
- HTTPVersionNotSupportedError,
40
- MaxComputeTimeReachedError,
41
- MissingSchemaError,
42
- InvalidMiddlewareWireError,
43
- PikkuMissingMetaError,
44
- } from './errors.js'
45
-
46
- describe('PikkuError', () => {
47
- test('should create error with default message', () => {
48
- const error = new PikkuError()
49
- assert.strictEqual(error.message, 'An error occurred')
50
- })
51
-
52
- test('should create error with custom message', () => {
53
- const error = new PikkuError('custom message')
54
- assert.strictEqual(error.message, 'custom message')
55
- })
56
-
57
- test('should be instance of Error', () => {
58
- const error = new PikkuError()
59
- assert.ok(error instanceof Error)
60
- })
61
-
62
- test('should be instance of PikkuError', () => {
63
- const error = new PikkuError()
64
- assert.ok(error instanceof PikkuError)
65
- })
66
-
67
- test('subclasses should be instanceof PikkuError', () => {
68
- assert.ok(new BadRequestError() instanceof PikkuError)
69
- assert.ok(new NotFoundError() instanceof PikkuError)
70
- assert.ok(new ForbiddenError() instanceof PikkuError)
71
- })
72
- })
73
-
74
- describe('getErrorResponse', () => {
75
- test('should return the correct error response for BadRequestError', () => {
76
- const error = new BadRequestError()
77
- const response = getErrorResponse(error)
78
- assert.deepStrictEqual(response, {
79
- status: 400,
80
- message:
81
- 'The server cannot or will not process the request due to client error (e.g., malformed request syntax).',
82
- })
83
- })
84
-
85
- test('should return the correct error response for NotFoundError', () => {
86
- const error = new NotFoundError()
87
- const response = getErrorResponse(error)
88
- assert.deepStrictEqual(response, {
89
- status: 404,
90
- message: 'The server cannot find the requested resource.',
91
- })
92
- })
93
-
94
- test('should return the correct error response for ForbiddenError', () => {
95
- const error = new ForbiddenError()
96
- const response = getErrorResponse(error)
97
- assert.deepStrictEqual(response, {
98
- status: 403,
99
- message:
100
- 'The client does not have permission to access the requested resource.',
101
- })
102
- })
103
-
104
- test('should return undefined for an unknown error', () => {
105
- class UnknownError extends Error {}
106
- const error = new UnknownError()
107
- const response = getErrorResponse(error)
108
- assert.strictEqual(response, undefined)
109
- })
110
-
111
- test('should return the correct error response for a custom error added to apiErrors', () => {
112
- class CustomError extends Error {}
113
- const customError = new CustomError()
114
- const customErrorDetails = { status: 400, message: 'Custom Error' }
115
-
116
- // Add the custom error to the apiErrors map
117
- addError(CustomError, customErrorDetails)
118
-
119
- const response = getErrorResponse(customError)
120
- assert.deepStrictEqual(response, customErrorDetails)
121
- })
122
- })
123
-
124
- describe('addErrors', () => {
125
- test('should register multiple errors at once', () => {
126
- class ErrA extends Error {}
127
- class ErrB extends Error {}
128
- addErrors([
129
- [ErrA, { status: 450, message: 'Error A' }],
130
- [ErrB, { status: 451, message: 'Error B' }],
131
- ])
132
- assert.deepStrictEqual(getErrorResponse(new ErrA()), {
133
- status: 450,
134
- message: 'Error A',
135
- })
136
- assert.deepStrictEqual(getErrorResponse(new ErrB()), {
137
- status: 451,
138
- message: 'Error B',
139
- })
140
- })
141
- })
142
-
143
- describe('all built-in error classes', () => {
144
- const errorCases: [string, any, number][] = [
145
- ['InvalidMiddlewareWireError', InvalidMiddlewareWireError, 500],
146
- ['PikkuMissingMetaError', PikkuMissingMetaError, 500],
147
- ['BadRequestError', BadRequestError, 400],
148
- ['UnauthorizedError', UnauthorizedError, 401],
149
- ['MissingSessionError', MissingSessionError, 401],
150
- ['InvalidSessionError', InvalidSessionError, 401],
151
- ['PaymentRequiredError', PaymentRequiredError, 402],
152
- ['ForbiddenError', ForbiddenError, 403],
153
- ['InvalidOriginError', InvalidOriginError, 403],
154
- ['NotFoundError', NotFoundError, 404],
155
- ['MethodNotAllowedError', MethodNotAllowedError, 405],
156
- ['NotAcceptableError', NotAcceptableError, 406],
157
- ['ProxyAuthenticationRequiredError', ProxyAuthenticationRequiredError, 407],
158
- ['RequestTimeoutError', RequestTimeoutError, 408],
159
- ['ConflictError', ConflictError, 409],
160
- ['GoneError', GoneError, 410],
161
- ['LengthRequiredError', LengthRequiredError, 411],
162
- ['PreconditionFailedError', PreconditionFailedError, 412],
163
- ['PayloadTooLargeError', PayloadTooLargeError, 413],
164
- ['URITooLongError', URITooLongError, 414],
165
- ['UnsupportedMediaTypeError', UnsupportedMediaTypeError, 415],
166
- ['RangeNotSatisfiableError', RangeNotSatisfiableError, 416],
167
- ['ExpectationFailedError', ExpectationFailedError, 417],
168
- ['UnprocessableContentError', UnprocessableContentError, 422],
169
- ['LockedError', LockedError, 423],
170
- ['TooManyRequestsError', TooManyRequestsError, 429],
171
- ['InternalServerError', InternalServerError, 500],
172
- ['NotImplementedError', NotImplementedError, 501],
173
- ['BadGatewayError', BadGatewayError, 502],
174
- ['ServiceUnavailableError', ServiceUnavailableError, 503],
175
- ['GatewayTimeoutError', GatewayTimeoutError, 504],
176
- ['HTTPVersionNotSupportedError', HTTPVersionNotSupportedError, 505],
177
- ['MaxComputeTimeReachedError', MaxComputeTimeReachedError, 524],
178
- ['MissingSchemaError', MissingSchemaError, 500],
179
- ]
180
-
181
- for (const [name, ErrorClass, expectedStatus] of errorCases) {
182
- test(`${name} should map to status ${expectedStatus}`, () => {
183
- const error = new ErrorClass()
184
- const response = getErrorResponse(error)
185
- assert.ok(response, `Expected error response for ${name}`)
186
- assert.strictEqual(response!.status, expectedStatus)
187
- assert.ok(response!.message.length > 0)
188
- })
189
-
190
- test(`${name} should be instance of PikkuError`, () => {
191
- const error = new ErrorClass()
192
- assert.ok(error instanceof PikkuError)
193
- })
194
- }
195
- })