@voltro/protocol 0.85.0 → 0.87.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 (80) hide show
  1. package/CHANGELOG.md +5987 -0
  2. package/README.md +14 -0
  3. package/THIRD-PARTY-NOTICES.md +1122 -31
  4. package/dist/apiRoleEndpoints.js +108 -0
  5. package/dist/apiRoleObservation.js +68 -0
  6. package/dist/apikey.d.ts +10 -0
  7. package/dist/approval.js +64 -0
  8. package/dist/approvalDescriptors.js +26 -0
  9. package/dist/auth.js +389 -0
  10. package/dist/boundedRing.js +27 -0
  11. package/dist/businessRule.js +11 -0
  12. package/dist/canonicalJson.js +14 -0
  13. package/dist/connection.js +73 -0
  14. package/dist/devActivity.js +4 -0
  15. package/dist/errorSchema.js +24 -0
  16. package/dist/errorValue.js +21 -0
  17. package/dist/event.js +110 -0
  18. package/dist/formCapture.js +12 -0
  19. package/dist/httpStreamMaxDuration.js +9 -0
  20. package/dist/idempotency.js +121 -0
  21. package/dist/idempotencyInput.js +123 -0
  22. package/dist/identity.js +5 -9
  23. package/dist/index.d.ts +1095 -139
  24. package/dist/index.js +54 -1700
  25. package/dist/inspect.d.ts +1 -1
  26. package/dist/inspect.js +14 -240
  27. package/dist/inspectBackfill.js +52 -0
  28. package/dist/inspectCommandRejection.js +21 -0
  29. package/dist/inspectProjection.js +133 -0
  30. package/dist/inspectStorageProjection.js +86 -0
  31. package/dist/inspectValueIdentity.js +4 -0
  32. package/dist/inspectWorkflowExecution.js +34 -0
  33. package/dist/inspectWorkflowQueuedStart.js +31 -0
  34. package/dist/jsonSchema.js +54 -0
  35. package/dist/jwt.d.ts +10 -0
  36. package/dist/jwt.js +1 -1
  37. package/dist/outbox.js +10 -0
  38. package/dist/pairing.js +75 -0
  39. package/dist/plugin.js +87 -0
  40. package/dist/pluginAccountMerge.js +88 -0
  41. package/dist/pluginNaming.js +32 -0
  42. package/dist/pluginPrivacy.js +166 -0
  43. package/dist/procedure.js +280 -0
  44. package/dist/publicApi.js +325 -0
  45. package/dist/queryOptionalSources.js +14 -0
  46. package/dist/reactivityChannel.js +34 -0
  47. package/dist/rest.d.ts +260 -64
  48. package/dist/rest.js +345 -499
  49. package/dist/restFormat.js +163 -0
  50. package/dist/restReceipt.js +43 -0
  51. package/dist/revalidate.js +13 -0
  52. package/dist/rowEquality.js +31 -0
  53. package/dist/rowPatch.js +182 -0
  54. package/dist/schemaShape.js +67 -0
  55. package/dist/scopes.js +273 -0
  56. package/dist/secretWindows.js +71 -0
  57. package/dist/serverErrorBus.js +15 -0
  58. package/dist/serviceCall.js +14 -0
  59. package/dist/session.d.ts +89 -6
  60. package/dist/session.js +62 -63
  61. package/dist/{sessionHeader-DriTZhmv.js → sessionHeader.js} +1 -1
  62. package/dist/ssrfPolicy.js +30 -0
  63. package/dist/storageAccess.js +14 -0
  64. package/dist/storeErrors.js +66 -0
  65. package/dist/storeScreenshots.js +90 -0
  66. package/dist/strictInput.js +27 -0
  67. package/dist/subscriptionEvent.js +37 -0
  68. package/dist/tenantSelection.js +40 -0
  69. package/dist/time.js +7 -0
  70. package/dist/undo.js +38 -0
  71. package/dist/validation.js +39 -0
  72. package/dist/webSocketGateway.js +16 -0
  73. package/dist/workflow.js +297 -0
  74. package/dist/workflowAccess.js +61 -0
  75. package/dist/workflowRestart.js +45 -0
  76. package/dist/workflowRetry.js +44 -0
  77. package/dist/workflowStartOutcome.js +30 -0
  78. package/package.json +5 -3
  79. package/dist/restFormat-BlgTLxm1.js +0 -298
  80. package/dist/scopes-ClywBij8.js +0 -548
@@ -0,0 +1,108 @@
1
+ //#region src/apiRoleEndpoints.ts
2
+ var e = (e, t) => {
3
+ if (!e || typeof e != "object" || Array.isArray(e) || ![Object.prototype, null].includes(Object.getPrototypeOf(e))) throw Error("Invalid role endpoint object");
4
+ let n = Object.create(null);
5
+ for (let r of Reflect.ownKeys(e)) {
6
+ let i = Object.getOwnPropertyDescriptor(e, r);
7
+ if (typeof r != "string" || !t.includes(r) || !i.enumerable || !("value" in i)) throw Error("Invalid role endpoint field");
8
+ n[r] = i.value;
9
+ }
10
+ return n;
11
+ }, t = (e, t, n = !1) => {
12
+ if (!Array.isArray(e) || e.length < +!n || e.length > t || Reflect.ownKeys(e).length !== e.length + 1) throw Error("Invalid role endpoint list");
13
+ let r = [];
14
+ for (let t = 0; t < e.length; t++) {
15
+ let n = Object.getOwnPropertyDescriptor(e, String(t));
16
+ if (!n?.enumerable || !("value" in n)) throw Error("Invalid role endpoint list item");
17
+ r.push(n.value);
18
+ }
19
+ return r;
20
+ }, n = /^(?:[A-Za-z][A-Za-z0-9_-]*\.)*[A-Za-z][A-Za-z0-9_-]*$/, r = /^(?:[A-Za-z_][A-Za-z0-9_-]*\.)*[A-Za-z_][A-Za-z0-9_-]*$/, i = [
21
+ "rpc",
22
+ "subscriptions",
23
+ "events",
24
+ "presence",
25
+ "workflows",
26
+ "schedules",
27
+ "directors",
28
+ "drainers",
29
+ "reapers",
30
+ "retention",
31
+ "rest",
32
+ "webhooks",
33
+ "inspect",
34
+ "cdc"
35
+ ], a = (r) => {
36
+ let a = e(r, [
37
+ "version",
38
+ "transport",
39
+ "roles"
40
+ ]);
41
+ if (a.version !== 1 || a.transport !== "compose-nginx" && a.transport !== "kubernetes-nginx") throw Error("Unknown role endpoint protocol");
42
+ let o = /* @__PURE__ */ new Set(), s = t(a.roles, 32, !0).map((r) => {
43
+ let a = e(r, [
44
+ "role",
45
+ "routes",
46
+ "workloads",
47
+ "httpPath",
48
+ "webSocketPath"
49
+ ]), s = a.role;
50
+ if (typeof s != "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(s) || o.has(s)) throw Error("Invalid or duplicate endpoint role");
51
+ o.add(s);
52
+ let c = t(a.workloads, 14).map((e) => {
53
+ if (typeof e != "string" || !i.includes(e)) throw Error("Unknown endpoint workload");
54
+ return e;
55
+ });
56
+ if (new Set(c).size !== c.length) throw Error("Duplicate endpoint workload");
57
+ let l = a.routes === null ? null : t(a.routes, 128).map((e) => {
58
+ if (typeof e != "string" || e.length > 191 || !n.test(e.endsWith(".*") ? e.slice(0, -2) : e)) throw Error("Invalid endpoint tag filter");
59
+ return e;
60
+ });
61
+ if (l && new Set(l).size !== l.length) throw Error("Duplicate endpoint tag filter");
62
+ let u = "/_voltro/roles/" + s;
63
+ if (a.webSocketPath !== u + "/ws" || a.httpPath !== (c.includes("rpc") ? u + "/rpc" : null)) throw Error("Role endpoints must use canonical same-origin paths");
64
+ return Object.freeze({
65
+ role: s,
66
+ routes: l && Object.freeze(l),
67
+ workloads: Object.freeze(c),
68
+ httpPath: a.httpPath,
69
+ webSocketPath: a.webSocketPath
70
+ });
71
+ });
72
+ return Object.freeze({
73
+ version: 1,
74
+ transport: a.transport,
75
+ roles: Object.freeze(s)
76
+ });
77
+ }, o = (e, t, n) => {
78
+ if (t.length > 191 || !r.test(t) || ![
79
+ "rpc",
80
+ "subscriptions",
81
+ "events"
82
+ ].includes(n)) throw Error("Invalid role endpoint request");
83
+ let i, a = -1, o = !1;
84
+ for (let r of e.roles) {
85
+ if (!r.workloads.includes(n)) continue;
86
+ let e = r.routes === null ? 0 : Math.max(-1, ...r.routes.map((e) => e.endsWith(".*") ? t.startsWith(e.slice(0, -1)) ? e.length : -1 : e === t ? 1024 + e.length : -1));
87
+ e > a ? (i = r, a = e, o = !1) : e >= 0 && e === a && (o = !0);
88
+ }
89
+ if (!i || o) throw Error(o ? "Ambiguous role endpoint" : "No role endpoint owns this tag and workload");
90
+ return i;
91
+ }, s = (e) => {
92
+ if (!/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/.test(e)) throw Error("Invalid role proxy API name");
93
+ return `/_voltro/role-api/api-${e}/ws`;
94
+ }, c = (e, t, n) => {
95
+ if (!/^[a-z][a-z0-9-]{0,63}$/.test(t.role) || !["http", "websocket"].includes(n)) throw Error("Invalid role transport");
96
+ let r = new URL(e);
97
+ if (![
98
+ "http:",
99
+ "https:",
100
+ "ws:",
101
+ "wss:"
102
+ ].includes(r.protocol) || r.username || r.password) throw Error("Invalid role endpoint origin");
103
+ let i = n === "http" ? t.httpPath : t.webSocketPath;
104
+ if (!i || i !== "/_voltro/roles/" + t.role + (n === "http" ? "/rpc" : "/ws")) throw Error("Missing or noncanonical role transport");
105
+ return r.protocol = n === "http" ? r.protocol === "https:" || r.protocol === "wss:" ? "https:" : "http:" : r.protocol === "https:" || r.protocol === "wss:" ? "wss:" : "ws:", r.pathname = (/^\/_voltro\/role-api\/api-[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}\/ws$/.test(r.pathname) ? r.pathname.slice(0, -3) : "") + i, r.search = "", r.hash = "", r.toString();
106
+ };
107
+ //#endregion
108
+ export { c as apiRoleEndpointUrl, s as apiRoleProxyBasePath, a as captureApiRoleEndpoints, o as selectApiRoleEndpoint };
@@ -0,0 +1,68 @@
1
+ import { API_WORKLOADS as e } from "./plugin.js";
2
+ import { Schema as t } from "effect";
3
+ //#region src/apiRoleObservation.ts
4
+ var n = t.Literals(e), r = t.Number.pipe(t.check(t.isFinite()), t.check(t.isGreaterThanOrEqualTo(0))), i = r.pipe(t.check(t.isInt())), a = i.pipe(t.check(t.isLessThanOrEqualTo(864e13))), o = t.Struct({
5
+ workload: n,
6
+ seconds: r
7
+ }), s = t.Struct({
8
+ replicaId: t.NonEmptyString,
9
+ startedAt: a,
10
+ role: t.NonEmptyString,
11
+ workloads: t.Array(n),
12
+ capturedAt: a,
13
+ publisher: t.Struct({
14
+ ready: t.Boolean,
15
+ stopped: t.Boolean,
16
+ pendingBuckets: i,
17
+ droppedBuckets: i,
18
+ rejectedSegments: i,
19
+ writeFailures: i,
20
+ observationErrors: i
21
+ }),
22
+ currentMeasuredSeconds: t.Array(t.Struct({
23
+ role: t.NonEmptyString,
24
+ workload: n,
25
+ seconds: r
26
+ })),
27
+ history: t.Struct({
28
+ state: t.Literals([
29
+ "pending",
30
+ "available",
31
+ "unavailable"
32
+ ]),
33
+ measuredSeconds: t.Array(o),
34
+ assessment: t.NullOr(t.Struct({
35
+ from: a,
36
+ until: a,
37
+ complete: t.Boolean,
38
+ missingBuckets: i.pipe(t.check(t.isLessThanOrEqualTo(288))),
39
+ incompleteWorkloads: t.Array(n),
40
+ reason: t.Literals([
41
+ "invalid-observation",
42
+ "incomplete",
43
+ "idle",
44
+ "observed"
45
+ ]),
46
+ totals: t.Array(t.Struct({
47
+ workload: n,
48
+ seconds: r,
49
+ share: r.pipe(t.check(t.isLessThanOrEqualTo(1)))
50
+ })),
51
+ splitCandidates: t.Array(n)
52
+ }))
53
+ })
54
+ }).pipe(t.check(t.makeFilter((e) => {
55
+ let t = (e) => new Set(e).size === e.length, n = (n) => t(n) && n.every((t) => e.workloads.some((e) => e === t));
56
+ if (!e.workloads.length || !t(e.workloads) || e.startedAt > e.capturedAt || !n(e.currentMeasuredSeconds.map((e) => e.workload)) || e.currentMeasuredSeconds.some((t) => t.role !== e.role) || !n(e.history.measuredSeconds.map((e) => e.workload))) return !1;
57
+ let r = e.history.assessment;
58
+ if (e.history.state !== "available") return r === null && e.history.measuredSeconds.length === 0;
59
+ if (!r || r.until - r.from !== 864e5 || r.until % 3e5 != 0 || r.until > e.capturedAt || !n(r.incompleteWorkloads) || !n(r.splitCandidates) || !n(r.totals.map((e) => e.workload))) return !1;
60
+ if (!r.complete) return r.totals.length === 0 && r.splitCandidates.length === 0 && ["incomplete", "invalid-observation"].includes(r.reason);
61
+ if (r.from < e.startedAt || r.missingBuckets !== 0 || r.incompleteWorkloads.length !== 0 || r.totals.length !== e.workloads.length) return !1;
62
+ let i = r.totals.reduce((e, t) => e + t.seconds, 0);
63
+ if (i > 86400 || r.reason !== (i === 0 ? "idle" : "observed") || r.totals.some((e) => Math.abs(e.share - (i === 0 ? 0 : e.seconds / i)) > 1e-9)) return !1;
64
+ let a = r.totals.filter((e) => e.share > .3).map((e) => e.workload), o = a.length >= 2 ? a : [];
65
+ return o.length === r.splitCandidates.length && o.every((e) => r.splitCandidates.includes(e));
66
+ }, { message: "Inconsistent API role observation" })));
67
+ //#endregion
68
+ export { s as ApiRoleObservationSchema };
package/dist/apikey.d.ts CHANGED
@@ -129,6 +129,13 @@ declare interface AuthStrategy {
129
129
  declare interface AuthStrategyInput {
130
130
  readonly headers: Readonly<Record<string, string | undefined>>;
131
131
  readonly clientId: number;
132
+ /** HTTP request target, supplied by REST transports. Request selectors may
133
+ * read an explicit tenant hint here; it is never authentication or authority.
134
+ * Absent for connection transports and non-HTTP callers. */
135
+ readonly http?: {
136
+ readonly path: string;
137
+ readonly query: string;
138
+ };
132
139
  /**
133
140
  * The app's DataStore, for a strategy that must READ to identify the caller.
134
141
  *
@@ -196,6 +203,9 @@ declare type StrategyResolution = {
196
203
 
197
204
  declare const Subject: Schema.Union<readonly [Schema.Struct<{
198
205
  readonly type: Schema.Literal<"user">;
206
+ /** A guest has a stable identity but has not linked a registered account.
207
+ * This identity mark survives session signing; it never grants authority. */
208
+ readonly kind: Schema.optional<Schema.Literal<"guest">>;
199
209
  readonly id: Schema.String;
200
210
  readonly tenantId: Schema.String;
201
211
  readonly scopes: Schema.optional<Schema.$Array<Schema.String>>;
@@ -0,0 +1,64 @@
1
+ import { Schema as e } from "effect";
2
+ //#region src/approval.ts
3
+ var t = class extends e.TaggedError()("ApprovalRequired", {
4
+ approvalId: e.String,
5
+ procedure: e.String,
6
+ expiresAt: e.String,
7
+ requiredScopes: e.Array(e.String),
8
+ reason: e.NullOr(e.String),
9
+ created: e.Boolean
10
+ }) {}, n = class extends e.TaggedError()("ApprovalNotFound", { approvalId: e.String }) {}, r = class extends e.TaggedError()("ApprovalSelfApproval", {
11
+ approvalId: e.String,
12
+ subjectId: e.NullOr(e.String)
13
+ }) {}, i = class extends e.TaggedError()("ApprovalRejected", {
14
+ approvalId: e.String,
15
+ decidedBy: e.NullOr(e.String),
16
+ note: e.NullOr(e.String)
17
+ }) {}, a = class extends e.TaggedError()("ApprovalExpired", {
18
+ approvalId: e.String,
19
+ expiredAt: e.String
20
+ }) {}, o = class extends e.TaggedError()("ApprovalNotPending", {
21
+ approvalId: e.String,
22
+ status: e.String
23
+ }) {}, s = class extends e.TaggedError()("ApprovalForbidden", {
24
+ approvalId: e.String,
25
+ required: e.NullOr(e.String),
26
+ message: e.String
27
+ }) {}, c = class extends e.TaggedError()("ApprovalUnavailable", {
28
+ procedure: e.String,
29
+ message: e.String
30
+ }) {}, l = e.Union([
31
+ t,
32
+ i,
33
+ a,
34
+ c
35
+ ]), u = e.Union([
36
+ n,
37
+ r,
38
+ a,
39
+ o,
40
+ s,
41
+ c
42
+ ]), d = e.Struct({
43
+ id: e.String,
44
+ procedure: e.String,
45
+ kind: e.Literals(["mutation", "action"]),
46
+ requestedBy: e.NullOr(e.String),
47
+ status: e.Literals([
48
+ "pending",
49
+ "approved",
50
+ "rejected",
51
+ "expired",
52
+ "consumed"
53
+ ]),
54
+ reason: e.NullOr(e.String),
55
+ requiredScopes: e.Array(e.String),
56
+ requestedAt: e.String,
57
+ expiresAt: e.String,
58
+ decidedBy: e.NullOr(e.String),
59
+ decidedAt: e.NullOr(e.String),
60
+ note: e.NullOr(e.String),
61
+ relation: e.Literals(["to-decide", "requested"])
62
+ });
63
+ //#endregion
64
+ export { u as ApprovalDecisionErrors, l as ApprovalErrors, a as ApprovalExpired, s as ApprovalForbidden, n as ApprovalNotFound, o as ApprovalNotPending, i as ApprovalRejected, t as ApprovalRequired, r as ApprovalSelfApproval, c as ApprovalUnavailable, d as PendingApproval };
@@ -0,0 +1,26 @@
1
+ import { ApprovalDecisionErrors as e, PendingApproval as t } from "./approval.js";
2
+ import { defineMutation as n, defineQuery as r } from "./procedure.js";
3
+ import { Schema as i } from "effect";
4
+ //#region src/approvalDescriptors.ts
5
+ var a = "__voltro.approvals.pending", o = "__voltro.approvals.decide", s = r({
6
+ name: a,
7
+ source: "_voltro_approvals",
8
+ input: i.Struct({ limit: i.optional(i.Number) }),
9
+ output: i.Array(t),
10
+ openAccess: "the answer is scoped to the caller — a row appears only if they requested it or hold its recorded approver scopes, so an anonymous caller sees nothing"
11
+ }), c = n({
12
+ name: o,
13
+ input: i.Struct({
14
+ approvalId: i.String,
15
+ decision: i.Literals(["approve", "reject"]),
16
+ note: i.optional(i.String)
17
+ }),
18
+ output: i.Struct({
19
+ approvalId: i.String,
20
+ status: i.Literals(["approved", "rejected"])
21
+ }),
22
+ error: e,
23
+ openAccess: "the approver authority is the PENDING ROW's own recorded scopes (plus an unconditional self-approval refusal), checked in-handler — a descriptor-level scope would have to be the union of every approval-requiring procedure in the app"
24
+ });
25
+ //#endregion
26
+ export { o as APPROVALS_DECIDE_TAG, a as APPROVALS_PENDING_TAG, c as approvalsDecideDescriptor, s as approvalsPendingQueryDescriptor };
package/dist/auth.js ADDED
@@ -0,0 +1,389 @@
1
+ import { RequestedTenantRefused as e, TenantSelectionRefused as t, isTenantSelectable as n, selectSubjectTenant as r } from "./tenantSelection.js";
2
+ import { Context as i, Schema as a, Struct as o } from "effect";
3
+ import { RpcMiddleware as s } from "effect/rpc";
4
+ //#region src/auth.ts
5
+ var c = a.Record(a.String, a.Unknown), l = a.optional(a.Array(a.String)), u = a.Struct({
6
+ type: a.Literal("user"),
7
+ kind: a.optional(a.Literal("guest")),
8
+ id: a.String,
9
+ tenantId: a.String,
10
+ scopes: l,
11
+ metadata: a.optional(c)
12
+ }), d = a.Struct({
13
+ type: a.Literal("apiKey"),
14
+ id: a.String,
15
+ tenantId: a.String,
16
+ scopes: l,
17
+ metadata: a.optional(c)
18
+ }), f = a.Struct({
19
+ type: a.Literal("serviceAccount"),
20
+ id: a.String,
21
+ tenantId: a.String,
22
+ auditActorId: a.optionalKey(a.NullOr(a.String)),
23
+ scopes: l,
24
+ metadata: a.optional(c)
25
+ }), p = a.Struct({
26
+ type: a.Literal("anonymous"),
27
+ id: a.Null,
28
+ tenantId: a.NullOr(a.String),
29
+ credentialRejected: a.optional(a.String)
30
+ }), m = a.Struct({
31
+ type: a.Literal("system"),
32
+ id: a.String,
33
+ tenantId: a.Null,
34
+ scopes: l,
35
+ metadata: a.optional(c)
36
+ }), h = a.Struct({
37
+ type: a.Literal("service"),
38
+ id: a.String,
39
+ service: a.String,
40
+ tenantId: a.Null,
41
+ scopes: l,
42
+ metadata: a.optional(c)
43
+ }), g = a.Union([
44
+ u,
45
+ d,
46
+ f,
47
+ p,
48
+ m,
49
+ h
50
+ ]), _ = a.Union([
51
+ u.mapFields(o.omit(["scopes"])),
52
+ d.mapFields(o.omit(["scopes"])),
53
+ f.mapFields(o.omit(["scopes"])),
54
+ p,
55
+ m.mapFields(o.omit(["scopes"])),
56
+ h.mapFields(o.omit(["scopes"]))
57
+ ]), v = (e) => {
58
+ if (e.type === "anonymous") return e;
59
+ let { scopes: t, ...n } = e;
60
+ return n;
61
+ }, y = (e) => e.scopes ?? [], b = (e, t) => ({
62
+ type: "anonymous",
63
+ id: null,
64
+ tenantId: e,
65
+ ...t === void 0 ? {} : { credentialRejected: t }
66
+ }), x = (e, t = ["admin:full"]) => ({
67
+ type: "system",
68
+ id: e,
69
+ tenantId: null,
70
+ scopes: t
71
+ }), S = (e) => ({
72
+ type: "service",
73
+ id: `service:${e}`,
74
+ service: e,
75
+ tenantId: null,
76
+ scopes: []
77
+ }), C = (e) => e.type === "service", w = (e) => e.type === "system" || e.type === "service", T = (e) => {
78
+ if (e.type === "system") return null;
79
+ if (e.type === "serviceAccount" && e.auditActorId !== void 0) return e.auditActorId;
80
+ if (e.type !== "apiKey") return e.id;
81
+ let t = e.metadata?.userId;
82
+ return typeof t == "string" && t !== "" ? t : e.id;
83
+ }, E = (e, t) => {
84
+ let n = e;
85
+ return {
86
+ type: "serviceAccount",
87
+ id: e.id ?? "system",
88
+ tenantId: t,
89
+ auditActorId: T(e),
90
+ scopes: y(e),
91
+ ...n.metadata === void 0 ? {} : { metadata: n.metadata }
92
+ };
93
+ }, D = (e) => e.type === "system", O = "impersonation", k = (e) => e.metadata?.impersonation ?? null, A = class extends i.Service()("@voltro/Subject") {}, j = class extends i.Service()("@voltro/ConnectionInfo") {}, M = class extends a.TaggedError()("Unauthenticated", { reason: a.optional(a.String) }) {
94
+ get message() {
95
+ return this.reason ?? "Unauthenticated";
96
+ }
97
+ }, N = class extends s.Service()("@voltro/AuthMiddleware", { error: a.Union([M, e]) }) {}, P = class extends s.Service()("@voltro/ConnectionInfoMiddleware") {}, F = /* @__PURE__ */ new WeakMap(), I = (e, t) => {
98
+ let n = { ...e };
99
+ return F.set(n, {
100
+ current: n,
101
+ resolve: t
102
+ }), n;
103
+ }, L = (e) => F.get(e)?.current ?? e, R = async (e, t) => {
104
+ let n = F.get(e);
105
+ if (n === void 0) return await t?.(e), e;
106
+ let r = await n.resolve();
107
+ if (r.type !== e.type || r.id !== e.id || r.tenantId !== e.tenantId || e.type === "service" && (r.type !== "service" || r.service !== e.service) || e.type === "user" && (r.type !== "user" || r.kind !== e.kind) || e.type === "serviceAccount" && (r.type !== "serviceAccount" || r.auditActorId !== e.auditActorId)) throw new M({ reason: "request identity or tenant changed; authenticate again" });
108
+ return F.set(r, {
109
+ current: r,
110
+ resolve: n.resolve
111
+ }), await t?.(r), n.current = r, r;
112
+ }, z = (e) => typeof e.mountRoutes == "function", B = (e) => Array.isArray(e) ? {
113
+ kind: "grant",
114
+ scopes: e
115
+ } : e, V = (e, t) => {
116
+ if (t.kind === "vetoed") throw new M({ reason: `${t.code}: ${t.message}` });
117
+ if (e.type === "anonymous") return {
118
+ subject: e,
119
+ removed: []
120
+ };
121
+ let n = y(e);
122
+ if (t.kind === "grant") {
123
+ if (t.scopes.length === 0) return {
124
+ subject: e,
125
+ removed: []
126
+ };
127
+ let r = [.../* @__PURE__ */ new Set([...n, ...t.scopes])];
128
+ return {
129
+ subject: {
130
+ ...e,
131
+ scopes: r
132
+ },
133
+ removed: []
134
+ };
135
+ }
136
+ let r = new Set(t.scopes), i = n.filter((e) => !r.has(e));
137
+ return {
138
+ subject: {
139
+ ...e,
140
+ scopes: [...r]
141
+ },
142
+ removed: i
143
+ };
144
+ }, H = async (e, t, n) => {
145
+ let r = n?.resolveScopes, i = B(r === void 0 ? [] : await r(e, t));
146
+ if (i.kind === "unavailable") return {
147
+ kind: "unavailable",
148
+ reason: i.reason
149
+ };
150
+ let a = V(e, i).subject;
151
+ if (a.type !== "anonymous") for (let e of n?.subjectGuards ?? []) {
152
+ let n = await e(a, t);
153
+ if (!n.ok) return {
154
+ kind: "vetoed",
155
+ code: n.code,
156
+ message: n.message
157
+ };
158
+ }
159
+ return {
160
+ kind: "resolved",
161
+ subject: a
162
+ };
163
+ }, U = 3e4, W = 1e4, G = (e) => `${e.type}\u0000${e.tenantId ?? ""}\u0000${e.id ?? ""}`, K = () => {
164
+ if (typeof process > "u") return;
165
+ let e = process.env.VOLTRO_AUTH_SCOPE_CACHE_TTL_MS;
166
+ if (e === void 0 || e === "") return;
167
+ let t = Number(e);
168
+ return Number.isFinite(t) && t >= 0 ? t : void 0;
169
+ }, q = (e = {}) => {
170
+ let t = e.ttlMs ?? K() ?? 3e4, n = e.maxEntries ?? 1e4, r = e.now ?? Date.now, i = /* @__PURE__ */ new Map(), a = () => {
171
+ if (i.size <= n) return;
172
+ let e = r();
173
+ for (let [t, n] of i) n.freshUntil <= e && i.delete(t);
174
+ for (let e of i.keys()) {
175
+ if (i.size <= n) break;
176
+ i.delete(e);
177
+ }
178
+ };
179
+ return {
180
+ ttlMs: t,
181
+ invalidate: (e) => {
182
+ i.delete(e);
183
+ },
184
+ invalidateAll: () => {
185
+ i.clear();
186
+ },
187
+ resolve: async (e, n) => {
188
+ let o = r();
189
+ if (t > 0) {
190
+ let t = i.get(e);
191
+ if (t && t.freshUntil > o) return {
192
+ decision: t.decision,
193
+ fresh: !1
194
+ };
195
+ }
196
+ let s = await n();
197
+ return t > 0 && s.kind !== "unavailable" && (i.set(e, {
198
+ decision: s,
199
+ freshUntil: o + t
200
+ }), a()), {
201
+ decision: s,
202
+ fresh: !0
203
+ };
204
+ }
205
+ };
206
+ }, J = (e) => typeof e.resolve == "function", Y = (e) => {
207
+ let t = e.authorization ?? e.Authorization;
208
+ if (t !== void 0) return /^Bearer\s+(.+)$/i.exec(t.trim())?.[1]?.trim();
209
+ }, X = async (e, i, a, o) => {
210
+ let s;
211
+ try {
212
+ s = await a.source(e, i);
213
+ } catch {
214
+ throw o("target-unavailable");
215
+ }
216
+ if (s === null) return;
217
+ if (typeof s != "string" || s.trim().length === 0) throw o("invalid-target");
218
+ if (!n(e)) throw o("subject-has-no-tenant");
219
+ let c;
220
+ try {
221
+ c = await a.memberships(e, i);
222
+ } catch {
223
+ throw o("memberships-unavailable");
224
+ }
225
+ try {
226
+ return r(e, s, c);
227
+ } catch (e) {
228
+ throw e instanceof t ? o(e.reason) : e;
229
+ }
230
+ }, Z = async (e, i, a, o) => {
231
+ if (!n(e)) return e;
232
+ let s = {
233
+ type: e.type,
234
+ id: e.id
235
+ }, c;
236
+ try {
237
+ c = await a.store.read(s);
238
+ } catch (e) {
239
+ throw o(`tenant selection unavailable: ${e instanceof Error ? e.message : String(e)}`);
240
+ }
241
+ if (c === null || c === e.tenantId) return e;
242
+ let l;
243
+ try {
244
+ l = await a.memberships(e, i);
245
+ } catch (e) {
246
+ throw o(`memberships unavailable: ${e instanceof Error ? e.message : String(e)}`);
247
+ }
248
+ try {
249
+ return r(e, c, l);
250
+ } catch (n) {
251
+ if (!(n instanceof t)) throw n;
252
+ try {
253
+ await a.store.clear(s);
254
+ } catch (e) {
255
+ throw o(`tenant selection unavailable: ${e instanceof Error ? e.message : String(e)}`);
256
+ }
257
+ return e;
258
+ }
259
+ }, Q = (e, t) => {
260
+ let n = Y(t);
261
+ if (n === void 0) return e;
262
+ let r = e.filter((e) => e.claimsBearerPrefix !== void 0 && e.claimsBearerPrefix !== "" && n.startsWith(e.claimsBearerPrefix));
263
+ if (r.length === 0) return e;
264
+ let i = new Set(r);
265
+ return [...r, ...e.filter((e) => !i.has(e))];
266
+ }, $ = (e, t) => {
267
+ if (e === "refuse") throw new M({ reason: "anonymous callers are refused" });
268
+ if (e === "no-tenant") return "";
269
+ if (e === "header") {
270
+ if (t === void 0 || t === "") throw new M({ reason: "tenant required (x-tenant header missing)" });
271
+ return t;
272
+ }
273
+ return "tenantId" in e ? e.tenantId : t !== void 0 && t !== "" ? t : e.headerOrTenant;
274
+ }, ee = (t, n) => {
275
+ let r = n?.resolveScopes, i = n?.subjectGuards ?? [], a = n?.tenantSelection !== void 0 || n?.requestedTenant !== void 0;
276
+ if (n?.memberships !== void 0 !== a) throw Error("composeAuthStrategies: memberships and tenant selection come together; `memberships` requires `tenantSelection` or `requestedTenant`; each tenant selector requires `memberships` to authorize its target.");
277
+ let o = n?.memberships !== void 0 && n.tenantSelection !== void 0 ? {
278
+ memberships: n.memberships,
279
+ store: n.tenantSelection
280
+ } : void 0, s = r !== void 0 || i.length > 0, c = !s || n?.scopeCache === !1 ? null : n?.scopeCache !== void 0 && J(n.scopeCache) ? n.scopeCache : q(n?.scopeCache ?? {}), l = async (a) => {
281
+ let l = n?.getStore?.(), u = l === void 0 ? a : {
282
+ ...a,
283
+ store: l
284
+ }, d;
285
+ for (let a of Q(t, u.headers)) {
286
+ let t = await a.resolve(u);
287
+ if (t.kind === "matched") {
288
+ let l = (e) => (n?.onStrategyFailed?.({
289
+ strategyId: a.id,
290
+ reason: e
291
+ }), new M({ reason: e })), d = n?.requestedTenant === void 0 || n.memberships === void 0 ? void 0 : await X(t.subject, u, {
292
+ source: n.requestedTenant,
293
+ memberships: n.memberships
294
+ }, (t) => (n?.onStrategyFailed?.({
295
+ strategyId: a.id,
296
+ reason: `requested tenant refused: ${t}`
297
+ }), new e({ reason: t })));
298
+ if (t.subject.type === "service") return { subject: {
299
+ ...t.subject,
300
+ scopes: []
301
+ } };
302
+ let f = d ?? (o === void 0 ? t.subject : await Z(t.subject, u, o, l)), p = f;
303
+ if (s) {
304
+ let e = async () => {
305
+ let e = r === void 0 ? {
306
+ kind: "grant",
307
+ scopes: []
308
+ } : B(await r(f, u));
309
+ if (e.kind === "unavailable" || i.length === 0) return e;
310
+ let t = V(f, e).subject, n = {
311
+ origin: "request",
312
+ headers: u.headers,
313
+ clientId: u.clientId,
314
+ store: u.store
315
+ };
316
+ for (let e of i) {
317
+ let r = await e(t, n);
318
+ if (!r.ok) return {
319
+ kind: "vetoed",
320
+ code: r.code,
321
+ message: r.message
322
+ };
323
+ }
324
+ return e;
325
+ }, { decision: t, fresh: o } = c === null ? {
326
+ decision: await e(),
327
+ fresh: !0
328
+ } : await c.resolve(G(f), e);
329
+ if (t.kind === "vetoed") {
330
+ let e = `${t.code}: ${t.message}`;
331
+ throw n?.onStrategyFailed?.({
332
+ strategyId: a.id,
333
+ reason: e
334
+ }), new M({ reason: e });
335
+ }
336
+ if (t.kind === "unavailable") {
337
+ let e = `scope resolution unavailable: ${t.reason}`;
338
+ throw n?.onStrategyFailed?.({
339
+ strategyId: a.id,
340
+ reason: e
341
+ }), new M({ reason: e });
342
+ }
343
+ let s = V(f, t);
344
+ o && s.removed.length > 0 && n?.onScopesNarrowed?.({
345
+ strategyId: a.id,
346
+ subjectType: f.type,
347
+ subjectId: f.id,
348
+ removed: s.removed,
349
+ granted: t.scopes
350
+ }), p = s.subject;
351
+ }
352
+ return t.credentialExpiresAt === void 0 ? { subject: p } : {
353
+ subject: p,
354
+ credentialExpiresAt: t.credentialExpiresAt
355
+ };
356
+ }
357
+ if (t.kind === "failed") {
358
+ n?.onStrategyFailed?.({
359
+ strategyId: a.id,
360
+ reason: t.reason
361
+ }), d = t.reason;
362
+ break;
363
+ }
364
+ }
365
+ if (n?.fallback) {
366
+ let e = await n.fallback(u);
367
+ return { subject: d !== void 0 && e.type === "anonymous" ? {
368
+ ...e,
369
+ credentialRejected: d
370
+ } : e };
371
+ }
372
+ if (d !== void 0) throw new M({ reason: `credential rejected: ${d}` });
373
+ return { subject: b($(n?.anonymous ?? "no-tenant", u.headers["x-tenant"])) };
374
+ };
375
+ return async (e) => {
376
+ let t = {
377
+ ...e,
378
+ headers: { ...e.headers }
379
+ }, n = await l(t), r = I(n.subject, async () => ({ ...(await l(t)).subject }));
380
+ return {
381
+ ...n,
382
+ subject: r
383
+ };
384
+ };
385
+ }, te = (e, t) => {
386
+ if (e.type === "anonymous") throw new M(t === void 0 ? {} : { reason: t });
387
+ };
388
+ //#endregion
389
+ export { N as AuthMiddleware, j as ConnectionInfo, P as ConnectionInfoMiddleware, W as DEFAULT_SCOPE_CACHE_MAX_ENTRIES, U as DEFAULT_SCOPE_CACHE_TTL_MS, O as IMPERSONATION_METADATA_KEY, g as Subject, _ as SubjectIdentity, A as SubjectService, M as Unauthenticated, b as anonymousSubject, V as applyScopeDecision, te as assertAuthenticated, I as bindSubjectAuthority, ee as composeAuthStrategies, L as currentSubjectAuthority, z as hasCallbackRoutes, w as isMachineSubject, C as isServiceSubject, D as isSystemSubject, q as makeScopeCache, Q as orderByBearerPrefix, k as rawImpersonationMark, R as reauthorizeSubject, H as resolveIdentityAuthority, G as scopeCacheKey, S as serviceSubject, T as subjectAuditActorId, v as subjectIdentity, x as systemSubject, E as tenantScopedSubject };