@voltro/runtime 0.85.0 → 0.86.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 (160) hide show
  1. package/CHANGELOG.md +666 -0
  2. package/THIRD-PARTY-NOTICES.md +5 -33
  3. package/dist/aggregate.js +42 -0
  4. package/dist/aggregateExtrema.js +80 -0
  5. package/dist/aggregateIvm.js +115 -0
  6. package/dist/analyticsMirror.js +228 -0
  7. package/dist/analyticsSink.js +38 -0
  8. package/dist/apiKeyUsage.js +33 -0
  9. package/dist/apiKeys.js +223 -0
  10. package/dist/apiKeysWiring.js +114 -0
  11. package/dist/approvalBuiltins.js +10 -0
  12. package/dist/approvals.js +269 -0
  13. package/dist/authMiddlewareLayer.js +47 -0
  14. package/dist/bindEvent.js +72 -0
  15. package/dist/bootListener.js +76 -0
  16. package/dist/bootRefusal.js +7 -0
  17. package/dist/bootStoreCodec.js +70 -0
  18. package/dist/businessRules.js +67 -0
  19. package/dist/changeClaimsTable.js +12 -0
  20. package/dist/circuitBreaker.js +72 -0
  21. package/dist/columnOnUpdate.js +23 -0
  22. package/dist/composeAnalytics.js +108 -0
  23. package/dist/computedQuery.js +4 -0
  24. package/dist/connectionBuiltins.js +81 -0
  25. package/dist/connectionCredentials.js +66 -0
  26. package/dist/connectionState.js +34 -0
  27. package/dist/connectionVault.js +410 -0
  28. package/dist/connectionsFacade.js +54 -0
  29. package/dist/coordinatedSchedule.js +139 -0
  30. package/dist/crdtHistory.js +138 -0
  31. package/dist/crdtMerge.js +179 -0
  32. package/dist/crdtVersionsTable.js +25 -0
  33. package/dist/credentialBound.js +12 -0
  34. package/dist/crud.js +72 -0
  35. package/dist/dataStore.js +679 -0
  36. package/dist/dataloader.js +61 -0
  37. package/dist/declaredTablesGuard.js +48 -0
  38. package/dist/defineExecutor.js +4 -0
  39. package/dist/dependencyGraph.js +32 -0
  40. package/dist/devices.js +228 -0
  41. package/dist/devicesWiring.js +168 -0
  42. package/dist/dialectReplicationAdapter.js +29 -0
  43. package/dist/dispatcher.js +447 -0
  44. package/dist/effectStore.js +71 -0
  45. package/dist/eventBus.js +260 -0
  46. package/dist/eventPublish.js +49 -0
  47. package/dist/events.js +193 -0
  48. package/dist/expectation.js +52 -0
  49. package/dist/expectationEvaluator.js +308 -0
  50. package/dist/experiment.js +96 -0
  51. package/dist/experimentEvaluator.js +245 -0
  52. package/dist/externalizedTasks.js +25 -0
  53. package/dist/fieldCipher.js +61 -0
  54. package/dist/fingerprint.js +21 -0
  55. package/dist/finops.js +42 -0
  56. package/dist/finopsAccountant.js +216 -0
  57. package/dist/handlerBody.js +8 -0
  58. package/dist/healthProbes.js +55 -0
  59. package/dist/httpClientSsrf.js +49 -0
  60. package/dist/httpClientTracing.js +11 -0
  61. package/dist/httpCompression.js +76 -0
  62. package/dist/httpKeepAlive.js +12 -0
  63. package/dist/httpRouteMounts.js +47 -0
  64. package/dist/idempotencyStore.js +70 -0
  65. package/dist/idleDetector.js +21 -0
  66. package/dist/index.d.ts +88 -69
  67. package/dist/index.js +144 -15292
  68. package/dist/insertRequiredColumns.js +19 -0
  69. package/dist/inspectWorkflow.js +1 -0
  70. package/dist/instanceMembership.js +98 -0
  71. package/dist/ivm.js +125 -0
  72. package/dist/kvDataStore.js +86 -0
  73. package/dist/kvFacade.js +32 -0
  74. package/dist/matcher.js +304 -0
  75. package/dist/memoryColumnDefaults.js +11 -0
  76. package/dist/memoryQueryJoins.js +114 -0
  77. package/dist/metrics.js +161 -0
  78. package/dist/observability.js +123 -0
  79. package/dist/observedGraph.js +52 -0
  80. package/dist/originGuard.js +116 -0
  81. package/dist/outbox.js +352 -0
  82. package/dist/pluginRefRules.js +65 -0
  83. package/dist/policyGuardResolver.js +55 -0
  84. package/dist/preview.js +62 -0
  85. package/dist/projectedRows.js +12 -0
  86. package/dist/provenance.js +63 -0
  87. package/dist/rangeIndex.js +89 -0
  88. package/dist/rawReadScope.js +17 -0
  89. package/dist/reaction.js +85 -0
  90. package/dist/reactiveConfig.js +11 -0
  91. package/dist/readClassification.js +57 -0
  92. package/dist/readRecorder.js +66 -0
  93. package/dist/rebac.js +104 -0
  94. package/dist/rebacInterceptor.js +81 -0
  95. package/dist/registry.js +29 -0
  96. package/dist/relevantFields.js +65 -0
  97. package/dist/replicaHealth.js +42 -0
  98. package/dist/replicaLocality.js +44 -0
  99. package/dist/replicaObservations.js +121 -0
  100. package/dist/replicaSelection.js +32 -0
  101. package/dist/replicatedDataStore.js +239 -0
  102. package/dist/requestLoader.js +7 -0
  103. package/dist/resumeCensus.js +28 -0
  104. package/dist/revalidation.js +22 -0
  105. package/dist/rowFilter.js +65 -0
  106. package/dist/rowStateBytes.js +45 -0
  107. package/dist/rpcBodyCap.js +63 -0
  108. package/dist/rpcConnections.js +83 -0
  109. package/dist/rpcDefectDiagnostics.js +15 -0
  110. package/dist/rpcServer.js +992 -0
  111. package/dist/runAsSystem.js +23 -0
  112. package/dist/rywPositionStore.js +84 -0
  113. package/dist/schedule.js +23 -0
  114. package/dist/scheduleBackfillRequests.js +151 -0
  115. package/dist/scheduleClaimsTable.js +11 -0
  116. package/dist/scheduleRunsTable.js +37 -0
  117. package/dist/scheduler.js +835 -0
  118. package/dist/schemaRegistry.js +65 -0
  119. package/dist/secretsResolver.js +35 -0
  120. package/dist/securityHeaders.js +33 -0
  121. package/dist/servePipeline.js +305 -0
  122. package/dist/serverOnlyAudit.js +66 -0
  123. package/dist/serverTracer.js +15 -0
  124. package/dist/serviceCredentials.js +40 -0
  125. package/dist/singleNodeOrchestrator.js +91 -0
  126. package/dist/sourceResolution.js +42 -0
  127. package/dist/storeMiddleware.js +880 -0
  128. package/dist/storeQuery.js +204 -0
  129. package/dist/storeRead.js +10 -0
  130. package/dist/subscriber.js +7 -0
  131. package/dist/subscriptionOutbox.js +139 -0
  132. package/dist/subscriptionRegistry.js +82 -0
  133. package/dist/subscriptionResume.js +132 -0
  134. package/dist/subscriptionSocketMetrics.js +65 -0
  135. package/dist/systemSubject.js +5 -0
  136. package/dist/tenantScope.js +23 -0
  137. package/dist/tenantSelection.js +27 -0
  138. package/dist/timeline.js +105 -0
  139. package/dist/traceContext.js +5 -0
  140. package/dist/traceSink.js +63 -0
  141. package/dist/traceSpansTable.js +29 -0
  142. package/dist/traceparent.js +34 -0
  143. package/dist/transactionSubject.js +12 -0
  144. package/dist/trustedProxy.js +155 -0
  145. package/dist/undo.js +129 -0
  146. package/dist/undoBuiltins.js +69 -0
  147. package/dist/undoCapture.js +74 -0
  148. package/dist/undoLogTable.js +16 -0
  149. package/dist/upsertBinding.js +20 -0
  150. package/dist/wakeOrchestrator.js +34 -0
  151. package/dist/wakeRegistry.js +71 -0
  152. package/dist/wakeRouter.js +63 -0
  153. package/dist/wakeSupervisor.js +62 -0
  154. package/dist/wakeupsTable.js +12 -0
  155. package/dist/webSocketGatewayRuntime.js +114 -0
  156. package/dist/webhookVerification.js +18 -0
  157. package/dist/wireColumnStrip.js +84 -0
  158. package/dist/workflowReadBuiltins.js +87 -0
  159. package/dist/workflowRuntime.js +708 -0
  160. package/package.json +7 -7
@@ -0,0 +1,223 @@
1
+ import { eq as e, generateId as t, inSet as n } from "@voltro/database";
2
+ import { createHash as r, randomBytes as i } from "node:crypto";
3
+ //#region src/apiKeys.ts
4
+ var a = "_voltro_api_keys", o = "actors", s = (e) => r("sha256").update(e, "utf8").digest("hex"), c = (e = "voltro_") => `${e}${i(30).toString("base64url")}`, l = (e) => ({
5
+ id: e.id,
6
+ name: e.name,
7
+ keyPrefix: e.keyPrefix,
8
+ tenantId: e.tenantId,
9
+ scopes: e.scopes ?? [],
10
+ lastUsedAt: e.lastUsedAt,
11
+ expiresAt: e.expiresAt,
12
+ revokedAt: e.revokedAt,
13
+ createdAt: e.createdAt,
14
+ createdBy: e.createdBy ?? null,
15
+ onBehalfOf: e.onBehalfOf ?? null,
16
+ ...e.metadata == null ? {} : { metadata: e.metadata }
17
+ }), u = (e, t) => e.revokedAt === null && (e.expiresAt === null || e.expiresAt > t), d = (e, n = {}) => {
18
+ let r = n.prefix ?? "voltro_", i = n.usage, o = async (n) => {
19
+ let i = c(r), o = t({
20
+ kind: "typeid",
21
+ prefix: "apikey"
22
+ }, a), l = n.scopes ?? [], u = n.expiresAt == null ? null : n.expiresAt instanceof Date ? n.expiresAt.getTime() : n.expiresAt;
23
+ return await e.ensureActor({
24
+ id: o,
25
+ displayName: n.name,
26
+ input: n
27
+ }), await e.insert({
28
+ id: o,
29
+ tenantId: n.tenantId ?? null,
30
+ name: n.name,
31
+ onBehalfOf: n.onBehalfOf ?? null,
32
+ hashedKey: s(i),
33
+ keyPrefix: i.slice(0, r.length + 6),
34
+ scopes: l,
35
+ lastUsedAt: null,
36
+ expiresAt: u,
37
+ revokedAt: null,
38
+ createdBy: n.createdBy ?? null,
39
+ createdAt: Date.now(),
40
+ ...n.metadata == null ? {} : { metadata: n.metadata }
41
+ }), {
42
+ id: o,
43
+ token: i,
44
+ keyPrefix: i.slice(0, r.length + 6),
45
+ name: n.name,
46
+ tenantId: n.tenantId ?? null,
47
+ scopes: l
48
+ };
49
+ }, d = async (t, n = Date.now()) => {
50
+ let r = await e.findByHash(t);
51
+ return !r || !u(r, n) ? null : (i === void 0 ? await e.patch(r.id, { lastUsedAt: n }) : i.touch(r.id, n), {
52
+ id: r.id,
53
+ tenantId: r.tenantId ?? "",
54
+ createdBy: r.createdBy ?? null,
55
+ onBehalfOf: r.onBehalfOf ?? null,
56
+ scopes: r.scopes ?? [],
57
+ ...r.metadata == null ? {} : { metadata: r.metadata }
58
+ });
59
+ };
60
+ return {
61
+ issue: o,
62
+ resolveByHash: d,
63
+ verify: (e, t) => d(s(e), t),
64
+ revoke: async (t, n, r = Date.now()) => {
65
+ let i = await e.findById(t);
66
+ return !i || (i.tenantId ?? null) !== n ? !1 : (await e.patch(t, { revokedAt: r }), !0);
67
+ },
68
+ rotate: async (t, n, r = Date.now()) => {
69
+ let i = await e.findById(t);
70
+ return !i || (i.tenantId ?? null) !== n ? null : (await e.patch(t, { revokedAt: r }), o({
71
+ tenantId: i.tenantId,
72
+ name: i.name,
73
+ scopes: i.scopes ?? [],
74
+ createdBy: i.createdBy,
75
+ onBehalfOf: i.onBehalfOf ?? null,
76
+ ...i.metadata == null ? {} : { metadata: i.metadata }
77
+ }));
78
+ },
79
+ list: async (t) => (await e.listByTenant(t)).map(l)
80
+ };
81
+ }, f = () => {
82
+ let e = /* @__PURE__ */ new Map(), t = /* @__PURE__ */ new Map();
83
+ return {
84
+ actors: t,
85
+ ensureActor: async (e) => {
86
+ t.has(e.id) || t.set(e.id, {
87
+ id: e.id,
88
+ kind: "apiKey",
89
+ displayName: e.displayName
90
+ });
91
+ },
92
+ insert: async (t) => {
93
+ e.set(t.id, t);
94
+ },
95
+ findByHash: async (t) => {
96
+ for (let n of e.values()) if (n.hashedKey === t) return n;
97
+ return null;
98
+ },
99
+ findById: async (t) => e.get(t) ?? null,
100
+ listByTenant: async (t) => {
101
+ let n = [...e.values()], r = 0;
102
+ for (let e of n) e.tenantId === t && (n[r++] = e);
103
+ return n.length = r, n;
104
+ },
105
+ patch: async (t, n) => {
106
+ let r = e.get(t);
107
+ r && e.set(t, {
108
+ ...r,
109
+ ...n
110
+ });
111
+ }
112
+ };
113
+ }, p = (e) => e == null ? null : e instanceof Date ? e.getTime() : typeof e == "number" ? e : typeof e == "string" ? new Date(e).getTime() : null, m = (e) => ({
114
+ id: String(e.id),
115
+ tenantId: e.tenantId ?? null,
116
+ name: String(e.name),
117
+ hashedKey: String(e.hashedKey),
118
+ keyPrefix: String(e.keyPrefix),
119
+ scopes: e.scopes ?? null,
120
+ lastUsedAt: p(e.lastUsedAt),
121
+ expiresAt: p(e.expiresAt),
122
+ revokedAt: p(e.revokedAt),
123
+ createdBy: e.createdBy ?? null,
124
+ onBehalfOf: e.onBehalfOf ?? null,
125
+ createdAt: p(e.createdAt) ?? 0,
126
+ ...e.metadata == null ? {} : { metadata: e.metadata }
127
+ }), h = async (e) => {
128
+ let t = await e.keys();
129
+ if (t.length === 0) return {
130
+ keys: 0,
131
+ planted: 0,
132
+ failed: []
133
+ };
134
+ let r = /* @__PURE__ */ new Set();
135
+ for (let i = 0; i < t.length; i += 500) {
136
+ let a = t.slice(i, i + 500).map((e) => e.id), s = await e.store.query({
137
+ table: o,
138
+ predicate: n("id", a),
139
+ order: [],
140
+ take: void 0,
141
+ skip: void 0,
142
+ projection: void 0
143
+ });
144
+ for (let e of s) typeof e.id == "string" && r.add(e.id);
145
+ }
146
+ let i = 0, a = [];
147
+ for (let n of t) if (!r.has(n.id)) try {
148
+ await e.apiKeyStore.ensureActor({
149
+ id: n.id,
150
+ displayName: n.name,
151
+ input: {
152
+ tenantId: n.tenantId,
153
+ name: n.name,
154
+ scopes: n.scopes ?? [],
155
+ createdBy: n.createdBy,
156
+ onBehalfOf: n.onBehalfOf ?? null,
157
+ ...n.metadata == null ? {} : { metadata: n.metadata }
158
+ }
159
+ }), i++;
160
+ } catch (e) {
161
+ a.push({
162
+ id: n.id,
163
+ reason: e instanceof Error ? e.message : String(e)
164
+ });
165
+ }
166
+ return {
167
+ keys: t.length,
168
+ planted: i,
169
+ failed: a
170
+ };
171
+ }, g = (e) => async (t, n) => {
172
+ let r = await e.findById(t);
173
+ if (r === null) return;
174
+ let i = r.requestCount ?? 0, a = r.lastUsedAt ?? 0;
175
+ await e.patch(t, {
176
+ requestCount: i + n.requests,
177
+ lastUsedAt: Math.max(a, n.lastUsedAt)
178
+ });
179
+ }, _ = (t, n = {}) => {
180
+ let r = n.ensureActor, i = async (e) => await t.query({
181
+ table: a,
182
+ predicate: e,
183
+ order: [],
184
+ take: void 0,
185
+ skip: void 0,
186
+ projection: void 0
187
+ }), s = (e) => {
188
+ let t = { ...e };
189
+ for (let e of [
190
+ "lastUsedAt",
191
+ "expiresAt",
192
+ "revokedAt",
193
+ "createdAt"
194
+ ]) e in t && typeof t[e] == "number" && (t[e] = new Date(t[e]));
195
+ return t;
196
+ };
197
+ return {
198
+ ensureActor: r === void 0 ? async (e) => {
199
+ await t.insertIgnore(o, {
200
+ id: e.id,
201
+ kind: "apiKey",
202
+ displayName: e.displayName
203
+ }, { conflictColumns: ["id"] });
204
+ } : (e) => r(e, t),
205
+ insert: async (e) => {
206
+ await t.insert(a, s(e));
207
+ },
208
+ findByHash: async (t) => {
209
+ let n = await i(e("hashedKey", t));
210
+ return n[0] ? m(n[0]) : null;
211
+ },
212
+ findById: async (t) => {
213
+ let n = await i(e("id", t));
214
+ return n[0] ? m(n[0]) : null;
215
+ },
216
+ listByTenant: async (t) => (await i(t === null ? void 0 : e("tenantId", t))).map(m).filter((e) => t === null || e.tenantId === t),
217
+ patch: async (e, n) => {
218
+ await t.update(a, e, s(n));
219
+ }
220
+ };
221
+ };
222
+ //#endregion
223
+ export { o as ACTORS_TABLE, a as API_KEYS_TABLE, _ as dataStoreApiKeyStore, c as generateApiKeyToken, d as makeApiKeyService, g as makeApiKeyUsageFlusher, f as memoryApiKeyStore, h as plantMissingApiKeyActors, s as sha256Hex };
@@ -0,0 +1,114 @@
1
+ import { Schema as e } from "effect";
2
+ import { ADMIN_SCOPE as t, APIKEY_ISSUE_ORG_SCOPE as n, APIKEY_ISSUE_OTHER_SCOPE as r, APIKEY_ISSUE_SELF_SCOPE as i, ScopeError as a } from "@voltro/protocol";
3
+ import { defineRestRoute as o, requireAnyScope as s, requireScope as c } from "@voltro/protocol/rest";
4
+ import { apiKeyStrategy as l } from "@voltro/protocol/apikey";
5
+ //#region src/apiKeysWiring.ts
6
+ var u = (e, t = {}) => l({
7
+ id: "voltro-apikey",
8
+ ...t.prefix ? { prefix: t.prefix } : {},
9
+ resolveKey: (t) => e.resolveByHash(t)
10
+ }), d = (e) => {
11
+ let t = e.subject;
12
+ return {
13
+ id: t.id ?? null,
14
+ tenantId: t.tenantId ?? null,
15
+ scopes: t.scopes ?? []
16
+ };
17
+ }, f = (l, u = "/v1/api-keys") => {
18
+ let f = e.Struct({
19
+ id: e.String,
20
+ name: e.String,
21
+ keyPrefix: e.String,
22
+ tenantId: e.NullOr(e.String),
23
+ scopes: e.Array(e.String),
24
+ lastUsedAt: e.NullOr(e.Number),
25
+ expiresAt: e.NullOr(e.Number),
26
+ revokedAt: e.NullOr(e.Number),
27
+ createdAt: e.Number,
28
+ createdBy: e.NullOr(e.String),
29
+ onBehalfOf: e.NullOr(e.String),
30
+ metadata: e.optional(e.NullOr(e.Record(e.String, e.Unknown)))
31
+ });
32
+ return [
33
+ o({
34
+ method: "POST",
35
+ path: `${u}/issue`,
36
+ summary: "Issue an API key (the token is returned ONCE).",
37
+ guards: [s([
38
+ t,
39
+ i,
40
+ n,
41
+ r
42
+ ])],
43
+ input: e.Struct({ body: e.Struct({
44
+ name: e.String,
45
+ scopes: e.optional(e.Array(e.String)),
46
+ expiresInDays: e.optional(e.Number),
47
+ onBehalfOf: e.optional(e.NullOr(e.String))
48
+ }) }),
49
+ output: e.Struct({
50
+ id: e.String,
51
+ token: e.String,
52
+ keyPrefix: e.String
53
+ }),
54
+ handler: async (e, o) => {
55
+ let s = e.body, c = d(o), u = new Set(c.scopes), f = (e) => u.has(t) || u.has(e), p = s.onBehalfOf === void 0 ? c.id : s.onBehalfOf;
56
+ if (p === null) {
57
+ if (!f(n)) throw new a({
58
+ required: n,
59
+ message: "not allowed to issue an organization key"
60
+ });
61
+ } else if (p !== c.id) {
62
+ if (!f(r)) throw new a({
63
+ required: r,
64
+ message: "not allowed to issue a key on behalf of another user"
65
+ });
66
+ } else if (!f(i)) throw new a({
67
+ required: i,
68
+ message: "not allowed to issue an api key"
69
+ });
70
+ let m = s.scopes ?? [...u];
71
+ if (!u.has(t)) {
72
+ let e = m.filter((e) => !u.has(e));
73
+ if (e.length > 0) throw new a({
74
+ required: String(e[0]),
75
+ message: `cannot issue a key with scopes you do not hold: ${e.join(", ")}`
76
+ });
77
+ }
78
+ let h = await l.issue({
79
+ tenantId: c.tenantId,
80
+ name: s.name,
81
+ scopes: m,
82
+ ...s.expiresInDays ? { expiresAt: Date.now() + s.expiresInDays * 864e5 } : {},
83
+ createdBy: c.id,
84
+ onBehalfOf: p
85
+ });
86
+ return {
87
+ id: h.id,
88
+ token: h.token,
89
+ keyPrefix: h.keyPrefix
90
+ };
91
+ }
92
+ }),
93
+ o({
94
+ method: "GET",
95
+ path: u,
96
+ summary: "List the caller tenant's API keys (no secrets).",
97
+ guards: [c(t)],
98
+ input: e.Struct({}),
99
+ output: e.Struct({ keys: e.Array(f) }),
100
+ handler: async (e, t) => ({ keys: [...await l.list(d(t).tenantId)] })
101
+ }),
102
+ o({
103
+ method: "POST",
104
+ path: `${u}/revoke`,
105
+ summary: "Revoke an API key by id.",
106
+ guards: [c(t)],
107
+ input: e.Struct({ body: e.Struct({ id: e.String }) }),
108
+ output: e.Struct({ ok: e.Boolean }),
109
+ handler: async (e, t) => ({ ok: await l.revoke(e.body.id, d(t).tenantId) })
110
+ })
111
+ ];
112
+ };
113
+ //#endregion
114
+ export { f as apiKeyManagementRoutes, u as frameworkApiKeyStrategy };
@@ -0,0 +1,10 @@
1
+ import { decideApproval as e, pendingApprovalsFor as t } from "./approvals.js";
2
+ //#region src/approvalBuiltins.ts
3
+ var n = (e) => e.request?.subject ?? null, r = async (e, r) => t(r.store, n(r), { limit: e.limit ?? 50 }), i = async (t, r) => e(r.store, {
4
+ approvalId: t.approvalId,
5
+ decision: t.decision,
6
+ approver: n(r),
7
+ ...t.note === void 0 ? {} : { note: t.note }
8
+ });
9
+ //#endregion
10
+ export { r as approvalsPendingExecutor, i as decideApprovalInvocation };
@@ -0,0 +1,269 @@
1
+ import { Effect as e } from "effect";
2
+ import { and as t, eq as n, generateId as r, id as i, inSet as a, registerRetention as o, retentionTtlMsFromEnv as s, table as c, text as l, timestamp as u } from "@voltro/database";
3
+ import { createHash as d, randomUUID as f } from "node:crypto";
4
+ import { ApprovalExpired as p, ApprovalForbidden as m, ApprovalNotFound as h, ApprovalNotPending as g, ApprovalRejected as _, ApprovalRequired as v, ApprovalSelfApproval as y, ApprovalUnavailable as b, checkGuardsEffect as x, isAuthenticatedGuard as S, isPolicyGuard as C, resolvePolicyAction as w } from "@voltro/protocol";
5
+ //#region src/approvals.ts
6
+ var T = "_voltro_approvals", E = 864e5, D = c(T, {
7
+ id: i({ prefix: "apv" }),
8
+ intentKey: l().maxLength(191),
9
+ procedure: l(),
10
+ kind: l(),
11
+ requestedBy: l().nullable(),
12
+ tenantId: l().nullable(),
13
+ payload: l(),
14
+ approverGuards: l(),
15
+ approverScopes: l(),
16
+ reason: l().nullable(),
17
+ status: l().default("pending"),
18
+ decidedBy: l().nullable(),
19
+ decidedAt: u().nullable(),
20
+ note: l().nullable(),
21
+ traceId: l().nullable(),
22
+ requestedAt: u().default("now"),
23
+ expiresAt: u(),
24
+ consumedAt: u().nullable()
25
+ }).index(["status", "expiresAt"]).index(["requestedBy"]), O = () => {
26
+ o({
27
+ source: "framework",
28
+ table: T,
29
+ timeColumn: "requestedAt",
30
+ ttlMs: s(process.env.VOLTRO_APPROVALS_TTL_HOURS, 720)
31
+ });
32
+ }, k = (e, t) => e.map((e) => S(e) ? { kind: "authenticated" } : C(e) ? {
33
+ kind: "policy",
34
+ action: w(e, t),
35
+ resourceType: e.resourceType,
36
+ resource: e.resource(t) ?? null
37
+ } : {
38
+ kind: "scope",
39
+ scope: typeof e.scope == "string" ? [e.scope] : [...e.scope],
40
+ mode: e.mode ?? "all",
41
+ resource: e.resource?.(t) ?? null
42
+ }), A = (e) => e.map((e) => e.kind === "authenticated" ? { authenticated: !0 } : e.kind === "policy" ? {
43
+ action: e.action,
44
+ resourceType: e.resourceType,
45
+ resource: () => e.resource ?? void 0
46
+ } : {
47
+ scope: e.scope,
48
+ mode: e.mode,
49
+ ...e.resource === null ? {} : { resource: () => e.resource ?? void 0 }
50
+ }), j = (e) => e.flatMap((e) => e.kind === "policy" ? [`${e.resourceType}:${e.action}`] : e.kind === "authenticated" ? ["authenticated"] : [...e.scope]), M = (e) => {
51
+ let t = (e) => {
52
+ if (Array.isArray(e)) return e.map(t);
53
+ if (typeof e == "object" && e) {
54
+ let n = e, r = Object.create(null);
55
+ for (let e of Object.keys(n).sort()) r[e] = t(n[e]);
56
+ return r;
57
+ }
58
+ return e;
59
+ };
60
+ return JSON.stringify(t(e) ?? null);
61
+ }, N = (e) => {
62
+ let t = [
63
+ e.procedure,
64
+ e.requestedBy ?? "",
65
+ e.tenantId ?? "",
66
+ e.payload,
67
+ e.nonce ?? ""
68
+ ].map((e) => `${e.length}:${e}`).join("");
69
+ return d("sha256").update(t, "utf8").digest("hex");
70
+ }, P = (e) => e instanceof Date ? e.toISOString() : typeof e == "string" ? e : (/* @__PURE__ */ new Date(0)).toISOString(), F = (e) => e instanceof Date ? e.getTime() : typeof e == "string" ? Date.parse(e) : 0, I = (e) => {
71
+ try {
72
+ let t = JSON.parse(String(e ?? "[]"));
73
+ return Array.isArray(t) ? t : [];
74
+ } catch {
75
+ return [];
76
+ }
77
+ }, L = async (e, t) => (await e.query({
78
+ table: "_voltro_approvals",
79
+ predicate: n("intentKey", t),
80
+ order: []
81
+ }))[0] ?? null, R = async (e, t) => (await e.query({
82
+ table: "_voltro_approvals",
83
+ predicate: n("id", t),
84
+ order: []
85
+ }))[0] ?? null, z = async (e, t, n) => {
86
+ let r = String(t.intentKey ?? ""), i = r.includes("#") ? r : `${r}#${String(t.id)}`;
87
+ await e.update(T, String(t.id), {
88
+ ...n,
89
+ intentKey: i
90
+ });
91
+ }, B = (e) => {
92
+ let t = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/.exec(e.trim());
93
+ if (t === null) return null;
94
+ let n = Number(t[1]);
95
+ if (!(Number.isFinite(n) && n > 0)) return null;
96
+ let r = t[2];
97
+ return n * (r === "ms" ? 1 : r === "s" ? 1e3 : r === "m" ? 6e4 : r === "h" ? 36e5 : 864e5);
98
+ }, V = (e) => {
99
+ let i = e.store, a = e.now ?? Date.now, o = e.defaultExpiryMs ?? 864e5;
100
+ O();
101
+ let s = (e) => {
102
+ if (e.expiresIn === void 0) return o;
103
+ let t = B(e.expiresIn);
104
+ if (t === null) throw Error(`requiresApproval.expiresIn must be an interval like '4h' / '30m' (got ${JSON.stringify(e.expiresIn)})`);
105
+ return t;
106
+ }, c = async (e, t, n) => {
107
+ let o = k(e.policy.approvers, e.input), c = r({
108
+ kind: "typeid",
109
+ prefix: "apv"
110
+ }, T), l = a();
111
+ await i.insertIgnore(T, {
112
+ id: c,
113
+ intentKey: t,
114
+ procedure: e.procedure,
115
+ kind: e.kind,
116
+ requestedBy: e.subject?.id ?? null,
117
+ tenantId: e.subject?.tenantId ?? null,
118
+ payload: n,
119
+ approverGuards: JSON.stringify(o),
120
+ approverScopes: JSON.stringify(j(o)),
121
+ reason: e.policy.reason ?? null,
122
+ status: "pending",
123
+ decidedBy: null,
124
+ decidedAt: null,
125
+ note: null,
126
+ traceId: e.traceId ?? null,
127
+ requestedAt: new Date(l),
128
+ expiresAt: new Date(l + s(e.policy)),
129
+ consumedAt: null
130
+ }, { conflictColumns: ["intentKey"] });
131
+ let u = await L(i, t);
132
+ if (u === null) throw new b({
133
+ procedure: e.procedure,
134
+ message: "the approval intent was written and could not be read back"
135
+ });
136
+ return u;
137
+ }, l = (e, t) => new v({
138
+ approvalId: String(e.id),
139
+ procedure: String(e.procedure),
140
+ expiresAt: P(e.expiresAt),
141
+ requiredScopes: j(I(e.approverGuards)),
142
+ reason: e.reason ?? null,
143
+ created: t
144
+ });
145
+ return { admit: async (e) => {
146
+ let r = M(e.input), o = N({
147
+ procedure: e.procedure,
148
+ requestedBy: e.subject?.id ?? null,
149
+ tenantId: e.subject?.tenantId ?? null,
150
+ payload: r,
151
+ nonce: e.nonce
152
+ }), s = await L(i, o);
153
+ if (s === null) throw l(await c(e, o, r), !0);
154
+ let u = String(s.status ?? "pending"), d = F(s.expiresAt);
155
+ if ((u === "pending" || u === "approved") && a() > d) throw await z(i, s, { status: "expired" }), new p({
156
+ approvalId: String(s.id),
157
+ expiredAt: P(s.expiresAt)
158
+ });
159
+ if (u === "pending") throw l(s, !1);
160
+ if (u === "rejected") throw await z(i, s, {}), new _({
161
+ approvalId: String(s.id),
162
+ decidedBy: s.decidedBy ?? null,
163
+ note: s.note ?? null
164
+ });
165
+ if (u === "approved") {
166
+ if (await i.updateMany("_voltro_approvals", {
167
+ status: "consumed",
168
+ consumedAt: new Date(a()),
169
+ intentKey: `${o}#${String(s.id)}`
170
+ }, { where: t(n("id", String(s.id)), n("status", "approved")) }) === 1) return;
171
+ throw s = await L(i, o), s === null ? l(await c(e, o, r), !0) : l(s, !1);
172
+ }
173
+ throw await z(i, s, {}), l(await c(e, o, r), !0);
174
+ } };
175
+ }, H, U = (e) => {
176
+ H = e;
177
+ }, W = () => H, G = () => {
178
+ H = void 0;
179
+ }, K = async (e) => {
180
+ if (e.policy === void 0) return;
181
+ let t = W();
182
+ if (t === void 0) throw new b({
183
+ procedure: e.procedure,
184
+ message: `${e.procedure} declares \`requiresApproval\` and no approvals gate is installed on this boot path, so the framework cannot record the intent or verify a decision. Refusing the call rather than running it unapproved.`
185
+ });
186
+ await t.admit({
187
+ procedure: e.procedure,
188
+ kind: e.kind,
189
+ policy: e.policy,
190
+ subject: e.subject ?? null,
191
+ input: e.input,
192
+ ...e.traceId === void 0 ? {} : { traceId: e.traceId }
193
+ });
194
+ }, q = async (r, i) => {
195
+ let a = i.now ?? Date.now, o = await R(r, i.approvalId);
196
+ if (o === null) throw new h({ approvalId: i.approvalId });
197
+ let s = String(o.status ?? "pending");
198
+ if (s !== "pending") throw new g({
199
+ approvalId: i.approvalId,
200
+ status: s
201
+ });
202
+ if (a() > F(o.expiresAt)) throw await z(r, o, { status: "expired" }), new p({
203
+ approvalId: i.approvalId,
204
+ expiredAt: P(o.expiresAt)
205
+ });
206
+ let c = i.approver?.id ?? null;
207
+ if (c === null) throw new m({
208
+ approvalId: i.approvalId,
209
+ required: null,
210
+ message: "an approval decision needs an identified subject — an anonymous caller cannot be the second human"
211
+ });
212
+ if (c === (o.requestedBy ?? null)) throw new y({
213
+ approvalId: i.approvalId,
214
+ subjectId: c
215
+ });
216
+ let l = A(I(o.approverGuards)), u = await e.runPromise(x(i.approver, l, JSON.parse(String(o.payload ?? "null"))));
217
+ if (u) throw new m({
218
+ approvalId: i.approvalId,
219
+ required: "_tag" in u && u._tag === "ScopeError" ? u.required : null,
220
+ message: u.message
221
+ });
222
+ let d = i.decision === "approve" ? "approved" : "rejected";
223
+ if (await r.updateMany("_voltro_approvals", {
224
+ status: d,
225
+ decidedBy: c,
226
+ decidedAt: new Date(a()),
227
+ note: i.note ?? null
228
+ }, { where: t(n("id", i.approvalId), n("status", "pending")) }) !== 1) {
229
+ let e = await R(r, i.approvalId);
230
+ throw new g({
231
+ approvalId: i.approvalId,
232
+ status: String(e?.status ?? "unknown")
233
+ });
234
+ }
235
+ return {
236
+ approvalId: i.approvalId,
237
+ status: d
238
+ };
239
+ }, J = async (t, n, r) => {
240
+ let i = n?.id ?? null;
241
+ if (i === null) return [];
242
+ let o = r?.now ?? Date.now, s = await t.query({
243
+ table: T,
244
+ predicate: a("status", ["pending", "approved"]),
245
+ order: []
246
+ }), c = [];
247
+ for (let t of s) {
248
+ if (o() > F(t.expiresAt)) continue;
249
+ let r = I(t.approverGuards), a = (t.requestedBy ?? null) === i, s = a ? "requested" : null;
250
+ a || await e.runPromise(x(n, A(r), JSON.parse(String(t.payload ?? "null")))) === null && String(t.status) === "pending" && (s = "to-decide"), s !== null && c.push({
251
+ id: String(t.id),
252
+ procedure: String(t.procedure),
253
+ kind: String(t.kind) === "action" ? "action" : "mutation",
254
+ requestedBy: t.requestedBy ?? null,
255
+ status: String(t.status ?? "pending"),
256
+ reason: t.reason ?? null,
257
+ requiredScopes: j(r),
258
+ requestedAt: P(t.requestedAt),
259
+ expiresAt: P(t.expiresAt),
260
+ decidedBy: t.decidedBy ?? null,
261
+ decidedAt: t.decidedAt == null ? null : P(t.decidedAt),
262
+ note: t.note ?? null,
263
+ relation: s
264
+ });
265
+ }
266
+ return c.sort((e, t) => t.requestedAt.localeCompare(e.requestedAt)).slice(0, r?.limit ?? 50);
267
+ }, Y = () => f();
268
+ //#endregion
269
+ export { T as APPROVALS_TABLE, E as DEFAULT_APPROVAL_EXPIRY_MS, D as _voltroApprovalsTable, N as approvalIntentKey, Y as approvalNonce, M as canonicalJson, G as clearApprovalGate, q as decideApproval, K as enforceApproval, W as getApprovalGate, U as installApprovalGate, V as makeApprovalGate, B as parseApprovalInterval, J as pendingApprovalsFor, A as rehydrateGuards, j as scopeStringsOf, k as serializeGuards };
@@ -0,0 +1,47 @@
1
+ import { applyConnectionCredential as e, getCredentialExpiry as t, recordCredentialExpiry as n } from "./connectionCredentials.js";
2
+ import { Context as r, Effect as i, Layer as a, Option as o, Schema as s } from "effect";
3
+ import { AuthMiddleware as c, ConnectionInfo as l, ConnectionInfoMiddleware as u, RequestedTenantRefused as d, SubjectService as f, Unauthenticated as p } from "@voltro/protocol";
4
+ import { Rpc as m } from "effect/rpc";
5
+ import { sessionExpiryFromHeaders as h } from "@voltro/protocol/session";
6
+ //#region src/authMiddlewareLayer.ts
7
+ var g = class extends r.Service()("@voltro/runtime/VerifiedCredentialLifetime") {}, _ = (e) => {
8
+ for (let t of e.requests.values()) if (m.isRpc(t) && [...t.middlewares].some((e) => e.key === c.key || e.key === u.key)) throw Error("withRpcAuthMiddleware requires a group without AuthMiddleware or ConnectionInfoMiddleware; apply the shared pair once");
9
+ return e.middleware(u).middleware(c);
10
+ }, v = (r) => {
11
+ let m = /* @__PURE__ */ new WeakSet(), _ = c.of((t, a) => {
12
+ m.add(a);
13
+ let { headers: o, client: c, rpc: l } = a;
14
+ return i.tryPromise({
15
+ try: async () => {
16
+ let t = await r.resolveSubject({
17
+ headers: e(c.id, o),
18
+ clientId: c.id
19
+ });
20
+ return n(c.id, t.credentialExpiresAt), t;
21
+ },
22
+ catch: (e) => e
23
+ }).pipe(i.catch((e) => s.is(s.Union([p, d]))(e) ? i.fail(e) : i.die(e)), i.flatMap((e) => {
24
+ let t = e.subject;
25
+ if (t.type !== "service") return i.succeed(e);
26
+ let n = r.serviceCallersFor?.(l._tag);
27
+ return n !== void 0 && n.includes(t.service) ? i.succeed(e) : i.fail(new p({ reason: `service '${t.service}' is not a caller of '${l._tag}' — a service credential reaches only the procedures that list it in \`service: { callers }\`` }));
28
+ }), i.flatMap((e) => i.provideService(t, f, e.subject).pipe(i.provideService(g, {
29
+ request: a,
30
+ credentialExpiresAt: e.credentialExpiresAt
31
+ }))));
32
+ });
33
+ return a.mergeAll(a.succeed(c, _), a.succeed(u, u.of((n, r) => i.gen(function* () {
34
+ let { headers: n, client: a, rpc: s } = r, l = yield* i.serviceOption(g), u = o.filter(l, (e) => e.request === r);
35
+ if (o.isNone(u) && m.has(r) && [...s.middlewares].some((e) => e.key === c.key)) throw Error("RPC authentication must run before ConnectionInfoMiddleware; compose the group with withRpcAuthMiddleware");
36
+ let d = o.isSome(u) ? u.value.credentialExpiresAt : t(a.id) ?? h(e(a.id, n)), f = n["idempotency-key"], p = n["voltro-resume-from"], _ = n["voltro-reconcile"], v = p !== void 0 && /^\d+$/.test(p) ? Number(p) : void 0;
37
+ return {
38
+ clientId: a.id,
39
+ ...f ? { idempotencyKey: f } : {},
40
+ ...d === void 0 ? {} : { credentialExpiresAt: d },
41
+ ...v !== void 0 && Number.isSafeInteger(v) ? { resumeFrom: v } : {},
42
+ ..._ !== void 0 && /^[a-zA-Z0-9_-]{1,128}$/.test(_) ? { reconcile: _ } : {}
43
+ };
44
+ }).pipe(i.flatMap((e) => i.provideService(n, l, e))))));
45
+ };
46
+ //#endregion
47
+ export { v as makeAuthMiddlewareLayers, _ as withRpcAuthMiddleware };