@mandateops/cli-linux-x64 0.0.0-stage → 0.7.1

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 (68) hide show
  1. package/LICENSE +55 -0
  2. package/README.md +175 -2
  3. package/audit-lab/README.md +194 -0
  4. package/audit-lab/bin/mandateops +0 -0
  5. package/audit-lab/contracts/contact-plain-text.vectors.json +85 -0
  6. package/audit-lab/contracts/history-reading.md +185 -0
  7. package/audit-lab/contracts/history-reading.vectors.json +284 -0
  8. package/audit-lab/contracts/profiles.md +161 -0
  9. package/audit-lab/contracts/properties.md +512 -0
  10. package/audit-lab/contracts/sdk-config.md +155 -0
  11. package/audit-lab/contracts/system-under-test.md +385 -0
  12. package/audit-lab/contracts/test-provider.md +350 -0
  13. package/audit-lab/lab/compose.audit.yml +181 -0
  14. package/audit-lab/lab/config/fault-control.json +14 -0
  15. package/audit-lab/lab/examples/agents/Dockerfile +28 -0
  16. package/audit-lab/lab/examples/agents/codeloc.cjs +199 -0
  17. package/audit-lab/lab/examples/agents/load.cjs +9 -0
  18. package/audit-lab/lab/examples/agents/package-lock.json +2840 -0
  19. package/audit-lab/lab/examples/agents/package.json +9 -0
  20. package/audit-lab/lab/examples/agents/python/mandateops_codeloc.py +271 -0
  21. package/audit-lab/lab/examples/agents/python/sitecustomize.py +51 -0
  22. package/audit-lab/lab/examples/agents/requirements-python.txt +522 -0
  23. package/audit-lab/lab/examples/agents/telemetry-router.cjs +272 -0
  24. package/audit-lab/lab/examples/test-provider/.dockerignore +4 -0
  25. package/audit-lab/lab/examples/test-provider/Dockerfile +28 -0
  26. package/audit-lab/lab/examples/test-provider/bun.lock +405 -0
  27. package/audit-lab/lab/examples/test-provider/package.json +42 -0
  28. package/audit-lab/lab/examples/test-provider/src/amount.ts +32 -0
  29. package/audit-lab/lab/examples/test-provider/src/app.ts +538 -0
  30. package/audit-lab/lab/examples/test-provider/src/auth.ts +30 -0
  31. package/audit-lab/lab/examples/test-provider/src/barrier.ts +262 -0
  32. package/audit-lab/lab/examples/test-provider/src/codeloc.ts +27 -0
  33. package/audit-lab/lab/examples/test-provider/src/config.ts +311 -0
  34. package/audit-lab/lab/examples/test-provider/src/connect.ts +204 -0
  35. package/audit-lab/lab/examples/test-provider/src/declaration.ts +270 -0
  36. package/audit-lab/lab/examples/test-provider/src/declared.ts +198 -0
  37. package/audit-lab/lab/examples/test-provider/src/domain.ts +193 -0
  38. package/audit-lab/lab/examples/test-provider/src/egress.ts +396 -0
  39. package/audit-lab/lab/examples/test-provider/src/flow.ts +263 -0
  40. package/audit-lab/lab/examples/test-provider/src/gate.ts +301 -0
  41. package/audit-lab/lab/examples/test-provider/src/main.ts +31 -0
  42. package/audit-lab/lab/examples/test-provider/src/notify.ts +157 -0
  43. package/audit-lab/lab/examples/test-provider/src/owner.ts +60 -0
  44. package/audit-lab/lab/examples/test-provider/src/payment.ts +103 -0
  45. package/audit-lab/lab/examples/test-provider/src/profile.ts +417 -0
  46. package/audit-lab/lab/examples/test-provider/src/request.ts +201 -0
  47. package/audit-lab/lab/examples/test-provider/src/rows.ts +173 -0
  48. package/audit-lab/lab/examples/test-provider/src/schema.ts +114 -0
  49. package/audit-lab/lab/examples/test-provider/src/signature.ts +86 -0
  50. package/audit-lab/lab/examples/test-provider/src/staged.ts +318 -0
  51. package/audit-lab/lab/examples/test-provider/src/store.ts +432 -0
  52. package/audit-lab/lab/examples/test-provider/src/traffic.ts +50 -0
  53. package/audit-lab/lab/examples/test-provider/src/webauthn.d.ts +11 -0
  54. package/audit-lab/lab/examples/test-provider/src/wire.ts +153 -0
  55. package/audit-lab/lab/examples/test-provider/tsconfig.build.json +9 -0
  56. package/audit-lab/lab/examples/test-provider/tsconfig.json +24 -0
  57. package/audit-lab/lab/images/capture/Dockerfile +15 -0
  58. package/audit-lab/lab/images/capture/LICENSE +201 -0
  59. package/audit-lab/lab/images/fault-control/Dockerfile +13 -0
  60. package/audit-lab/lab/images/fault-control/LICENSE +21 -0
  61. package/audit-lab/lab/images/provider-store/Dockerfile +4 -0
  62. package/audit-lab/lab/images/provider-store/LICENSE +23 -0
  63. package/audit-lab/lab/images/telemetry/Dockerfile +14 -0
  64. package/audit-lab/lab/images/telemetry/LICENSE +201 -0
  65. package/audit-lab/lab/scripts/compose-down.sh +143 -0
  66. package/audit-lab/lab/scripts/compose-lib.sh +632 -0
  67. package/audit-lab/lab/scripts/compose-up.sh +240 -0
  68. package/package.json +16 -4
@@ -0,0 +1,157 @@
1
+ import { createHmac, randomUUID } from "node:crypto";
2
+ import { MAX_RECORDS_PER_RUN, ProviderError } from "./domain.js";
3
+ import type { Effect } from "./domain.js";
4
+
5
+ /** Where notifications go and the secret that signs them. */
6
+ export type NotifyTarget = Readonly<{
7
+ url: URL;
8
+ secret: string;
9
+ timeoutMs: number;
10
+ }>;
11
+
12
+ /** One delivery as the provider records it, after it ended. */
13
+ export type DeliveryRecord = Readonly<{
14
+ effectId: string;
15
+ deliveryId: string;
16
+ issued: number;
17
+ /** When sending began; null when nothing was sent. */
18
+ sentAt: string | null;
19
+ deliveredAt: string;
20
+ /** The backend's HTTP status; null when nothing answered. */
21
+ status: number | null;
22
+ }>;
23
+
24
+ /** What the notifier needs from the provider's records. */
25
+ export type NotificationLedger = Readonly<{
26
+ effect: (effectId: string) => Promise<Effect>;
27
+ recordDelivery: (delivery: DeliveryRecord) => Promise<void>;
28
+ }>;
29
+
30
+ /** How one issued notification is delivered. */
31
+ export type NotifyPlan = Readonly<{ hold: boolean; copies: number }>;
32
+
33
+ /** Most deliveries one control call may send at once, or hold. */
34
+ export const MAX_NOTIFY_COPIES = 8;
35
+ /** Signature header the backend verifies: `sha256=` and the hex HMAC. */
36
+ export const SIGNATURE_HEADER = "x-provider-signature";
37
+
38
+ type Pending = Readonly<{ effect: Effect; deliveryId: string; issued: number }>;
39
+
40
+ /** An instant to the microsecond on the process's one clock. */
41
+ function instant(): string {
42
+ const micros = BigInt(
43
+ Math.round((performance.timeOrigin + performance.now()) * 1000),
44
+ );
45
+ const whole = new Date(Number(micros / 1000n)).toISOString().slice(0, 19);
46
+ return `${whole}.${(micros % 1_000_000n).toString().padStart(6, "0")}Z`;
47
+ }
48
+
49
+ /** The body the backend receives: which effect, which delivery, its terms. */
50
+ export function notificationBody(pending: Pending): string {
51
+ const { instruction } = pending.effect;
52
+ return JSON.stringify({
53
+ deliveryId: pending.deliveryId,
54
+ effectId: pending.effect.effectId,
55
+ event: "payout.paid",
56
+ payment: instruction.payment,
57
+ amount: instruction.amount,
58
+ currency: instruction.currency,
59
+ asset: instruction.asset,
60
+ network: instruction.network,
61
+ });
62
+ }
63
+
64
+ export function sign(secret: string, body: string): string {
65
+ return `sha256=${createHmac("sha256", secret).update(body).digest("hex")}`;
66
+ }
67
+
68
+ /**
69
+ * Issues notifications of committed effects and delivers them to the
70
+ * backend, at once, together or held back until released. Every delivery is
71
+ * recorded once it ends, so record order is delivery order; `issued` keeps the
72
+ * order the runner asked for. Without a target nothing is sent and each
73
+ * delivery is recorded unanswered. Nothing here retries.
74
+ */
75
+ export class Notifier {
76
+ private issued = 0;
77
+ private held: Pending[] = [];
78
+
79
+ constructor(
80
+ private readonly records: NotificationLedger,
81
+ private readonly target: NotifyTarget | undefined,
82
+ private readonly recordLimit: number = MAX_RECORDS_PER_RUN,
83
+ ) {}
84
+
85
+ async issue(
86
+ effectId: string,
87
+ plan: NotifyPlan,
88
+ ): Promise<readonly (number | null)[]> {
89
+ const effect = await this.records.effect(effectId);
90
+ if (this.issued + plan.copies > this.recordLimit)
91
+ throw new ProviderError(409, "notification_limit");
92
+ const pending = Array.from({ length: plan.copies }, () => ({
93
+ effect,
94
+ deliveryId: randomUUID(),
95
+ issued: ++this.issued,
96
+ }));
97
+ if (plan.hold) {
98
+ if (this.held.length + pending.length > MAX_NOTIFY_COPIES)
99
+ throw new ProviderError(409, "held_limit");
100
+ this.held.push(...pending);
101
+ return [];
102
+ }
103
+ return Promise.all(pending.map((one) => this.deliver(one)));
104
+ }
105
+
106
+ /** Delivers every held notification in the order it was issued. */
107
+ async release(): Promise<readonly (number | null)[]> {
108
+ const held = this.held.splice(0);
109
+ const answers: (number | null)[] = [];
110
+ for (const one of held) answers.push(await this.deliver(one));
111
+ return answers;
112
+ }
113
+
114
+ reset(): void {
115
+ this.held = [];
116
+ this.issued = 0;
117
+ }
118
+
119
+ private async deliver(pending: Pending): Promise<number | null> {
120
+ const sentAt = this.target ? instant() : null;
121
+ const status = this.target ? await this.send(this.target, pending) : null;
122
+ await this.records.recordDelivery({
123
+ effectId: pending.effect.effectId,
124
+ deliveryId: pending.deliveryId,
125
+ issued: pending.issued,
126
+ sentAt,
127
+ deliveredAt: instant(),
128
+ status,
129
+ });
130
+ return status;
131
+ }
132
+
133
+ private async send(
134
+ target: NotifyTarget,
135
+ pending: Pending,
136
+ ): Promise<number | null> {
137
+ const body = notificationBody(pending);
138
+ try {
139
+ const response = await fetch(target.url, {
140
+ method: "POST",
141
+ redirect: "manual",
142
+ signal: AbortSignal.timeout(target.timeoutMs),
143
+ headers: {
144
+ "content-type": "application/json",
145
+ [SIGNATURE_HEADER]: sign(target.secret, body),
146
+ },
147
+ body,
148
+ });
149
+ await response.body?.cancel();
150
+ return response.status;
151
+ } catch {
152
+ // No answer: the delivery did not reach the backend as far as anything
153
+ // independent shows.
154
+ return null;
155
+ }
156
+ }
157
+ }
@@ -0,0 +1,60 @@
1
+ import { Kysely, PostgresDialect } from "kysely";
2
+ import { Pool } from "pg";
3
+ import { z } from "zod";
4
+ import type { Database, Queries } from "./rows.js";
5
+ import { createSchema } from "./schema.js";
6
+
7
+ const OWNER_LOCK = 718303;
8
+
9
+ /** How the store's connections are bounded. */
10
+ export type PoolLimits = Readonly<{
11
+ poolConnections: number;
12
+ connectionTimeoutMs: number;
13
+ statementTimeoutMs: number;
14
+ idleTransactionTimeoutMs: number;
15
+ }>;
16
+ export type PoolConfig = PoolLimits & Readonly<{ databaseUrl: string }>;
17
+
18
+ const poolOf = (config: PoolConfig, connections: number): Pool =>
19
+ new Pool({
20
+ connectionString: config.databaseUrl,
21
+ max: connections,
22
+ connectionTimeoutMillis: config.connectionTimeoutMs,
23
+ statement_timeout: config.statementTimeoutMs,
24
+ idle_in_transaction_session_timeout: config.idleTransactionTimeoutMs,
25
+ // A pool of one never lets go of the session that holds the owner lock.
26
+ idleTimeoutMillis: connections === 1 ? 0 : undefined,
27
+ });
28
+
29
+ export const servingPool = (config: PoolConfig): Pool =>
30
+ poolOf(config, config.poolConnections);
31
+ export const ownerPool = (config: PoolConfig): Pool => poolOf(config, 1);
32
+
33
+ export const queriesOver = (pool: Pool): Queries =>
34
+ new Kysely<Database>({ dialect: new PostgresDialect({ pool }) });
35
+
36
+ /** Refuses anything but a disposable database this process alone owns. */
37
+ export async function claimDatabase(owner: Queries): Promise<void> {
38
+ const database = await owner
39
+ .selectNoFrom((builder) =>
40
+ builder.fn<string>("current_database").as("name"),
41
+ )
42
+ .executeTakeFirst();
43
+ if (
44
+ !z
45
+ .object({ name: z.string().regex(/^audit_lab_[a-z0-9_]+$/) })
46
+ .safeParse(database).success
47
+ ) {
48
+ throw new Error("a disposable audit_lab_* database is required");
49
+ }
50
+ // The barrier lives in this process, so one process owns the database.
51
+ const lock = await owner
52
+ .selectNoFrom((builder) =>
53
+ builder
54
+ .fn<boolean>("pg_try_advisory_lock", [builder.val(OWNER_LOCK)])
55
+ .as("locked"),
56
+ )
57
+ .executeTakeFirst();
58
+ if (lock?.locked !== true) throw new Error("provider database already owned");
59
+ await createSchema(owner);
60
+ }
@@ -0,0 +1,103 @@
1
+ import type { RefusalAttempt } from "./barrier.js";
2
+ import type { Effect, ExecutionResult, RejectionReason } from "./domain.js";
3
+ import type {
4
+ PaymentRequest,
5
+ PaymentWire,
6
+ RefusalReplay,
7
+ WireReply,
8
+ } from "./wire.js";
9
+
10
+ type Terms = PaymentRequest["instruction"];
11
+ /** Asked inside the ledger's serialised step, by a key a refusal can still reach. */
12
+ export type DeclineCheck = (terms: Terms) => boolean;
13
+
14
+ /**
15
+ * Durable payment records; a store owns them and nothing here sees how. A key
16
+ * already bound decides the outcome in the transaction, so a refusal is only
17
+ * ever taken by a key with none.
18
+ */
19
+ export type PaymentLedger = Readonly<{
20
+ execute: (
21
+ request: PaymentRequest,
22
+ refusals: RefusalReplay,
23
+ declines: DeclineCheck,
24
+ ) => Promise<ExecutionResult>;
25
+ /** Records a refusal a format made before any money step. */
26
+ reject: (request: PaymentRequest, reason: RejectionReason) => Promise<void>;
27
+ }>;
28
+ /** A payment request and the provider in the run's list that it reached. */
29
+ export type ProviderPayment = PaymentRequest & Readonly<{ provider: string }>;
30
+
31
+ /**
32
+ * The one ledger every provider of a run shares, so money is counted across
33
+ * them all; a key is bound per provider, as each provider keeps its own keys.
34
+ */
35
+ export type SharedLedger = Readonly<{
36
+ execute: (
37
+ payment: ProviderPayment,
38
+ refusals: RefusalReplay,
39
+ declines: DeclineCheck,
40
+ ) => Promise<ExecutionResult>;
41
+ reject: (payment: ProviderPayment, reason: RejectionReason) => Promise<void>;
42
+ }>;
43
+
44
+ /** The shared ledger as one provider of the run writes to it. */
45
+ export const providerLedger = (
46
+ shared: SharedLedger,
47
+ provider: string,
48
+ ): PaymentLedger => ({
49
+ execute: (request, refusals, declines) =>
50
+ shared.execute({ ...request, provider }, refusals, declines),
51
+ reject: (request, reason) => shared.reject({ ...request, provider }, reason),
52
+ });
53
+
54
+ /** Says whether the next request is declined; one attempt per request. */
55
+ export type RefusalGate = Readonly<{
56
+ attempt: () => RefusalAttempt;
57
+ }>;
58
+ export type RecordCounter = Readonly<{ recorded: () => void }>;
59
+
60
+ export type PaymentStep = Readonly<{
61
+ ledger: PaymentLedger;
62
+ refusal: RefusalGate;
63
+ counter: RecordCounter;
64
+ wire: Pick<PaymentWire, "declined" | "conflict" | "refusals">;
65
+ }>;
66
+ export type Settlement =
67
+ | Readonly<{ kind: "answered"; reply: WireReply }>
68
+ | Readonly<{ kind: "committed"; effect: Effect; created: boolean }>;
69
+
70
+ /** Runs the ledger; a refusal survives unless it reached the record. */
71
+ async function recorded(
72
+ { ledger, refusal, wire }: PaymentStep,
73
+ payment: PaymentRequest,
74
+ ): Promise<ExecutionResult> {
75
+ const attempt = refusal.attempt();
76
+ try {
77
+ const result = await ledger.execute(payment, wire.refusals, attempt.takes);
78
+ attempt.settled();
79
+ return result;
80
+ } catch (error) {
81
+ attempt.abandon();
82
+ throw error;
83
+ }
84
+ }
85
+
86
+ /** The one money step every format shares: refuse, or commit through the ledger. */
87
+ export async function settle(
88
+ step: PaymentStep,
89
+ payment: PaymentRequest,
90
+ ): Promise<Settlement> {
91
+ const { counter, wire } = step;
92
+ const result = await recorded(step, payment);
93
+ counter.recorded();
94
+ if (result.kind === "declined")
95
+ return { kind: "answered", reply: wire.declined(payment) };
96
+ if (result.kind === "key_conflict")
97
+ return { kind: "answered", reply: wire.conflict(payment) };
98
+ return {
99
+ kind: "committed",
100
+ effect: result.effect,
101
+ created: result.created,
102
+ };
103
+ }