@grovemotorco/manifold 0.0.0-stage → 0.0.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.
@@ -0,0 +1,640 @@
1
+ import { $ as JwtAlgorithm, $t as SourceConfig, A as ConfigSource, At as RelayTimeoutMs, B as EventTypeGlob, Bt as RouteConfig, C as AutoPauseThreshold, Ct as RejectionCounter, D as ConfigDocumentInput, Dt as RelayConfig, E as ConfigDocument, Et as Rejections, F as DeliveryRecord, Ft as RequestStatus, G as HandshakeSpec, Gt as SecretEncoding, H as ExtractorPart, Ht as RouteId, I as DeliveryStatus, It as ResolvedVerification, J as HeaderName, Jt as SecretInfo, K as HashAlgorithm, Kt as SecretHeaderInfo, L as ERROR_STATUS, Lt as RetentionDays, M as DedupeWindowSeconds, Mt as RequestDetail, N as DeliveryDetail, Nt as RequestId, O as ConfigRelay, Ot as RelayConfigInput, P as DeliveryId, Pt as RequestRecord, Q as JsonChallengeHandshake, Qt as SigningSecretInfo, R as ErrorBody, Rt as RetryPolicy, S as AuditRecord, St as Principal, T as ClaimRequirement, Tt as RejectionRecord, U as FINISHED_DELIVERY_STATUSES, Ut as RouteState, V as Extractor, Vt as RouteConfigInput, W as Fingerprint, Wt as RouteView, X as IngestAck, Xt as SignatureEncoding, Y as HmacVerify, Yt as SecretValue, Z as IssuedSigningSecret, Zt as SignatureFormat, _ as ApplyResult, _t as PauseReason, a as LOCAL_ID_PREFIX, an as TargetLabel, at as ListenerInfo, b as AttemptStatus, bt as PresetId, c as idPattern, cn as ValueSource, ct as ListenersSetting, d as isLocalId, dn as VerifyTemplate, dt as LocalId, en as SourceConfigInput, et as JwtVerify, f as makeIdGenerator, fn as VerifyType, ft as MaxBodyBytes, g as ApplyChanges, gt as Page, h as newLocalId, hn as sourceConfigFields, ht as NoneVerify, i as IdPrefix, in as TIMINGS, it as ListenTokenInfo, j as Count, jt as RelayView, k as ConfigRoute, kt as RelayId, l as idTime, ln as VerifyOverride, lt as LocalAttemptKind, m as newId, mn as routeConfigFields, mt as Millis, n as IdGenerator, nn as SourceStats, nt as LIMITS, o as ULID_PATTERN, on as TokenVerify, ot as ListenerName, p as minIdAt, pn as relayConfigFields, pt as MiB, q as HeaderMap, qt as SecretHeaders, r as IdGeneratorOptions, rn as SourceView, rt as ListenTokenId, s as idAt, sn as Tolerance, st as ListenerSessionId, t as ID_PREFIXES, tn as SourceKey, tt as KiB, u as isId, un as VerifySpec, ut as LocalAttemptRecord, v as AttemptId, vt as PayloadTemplate, w as BodyPath, wt as RejectionReason, x as AuditAction, xt as PresetResponse, y as AttemptRecord, yt as Preset, z as ErrorCode, zt as Revision } from "./ids-Ced7gYBp.js";
2
+ import * as Context from "effect/Context";
3
+ import * as Effect from "effect/Effect";
4
+ import * as Layer from "effect/Layer";
5
+ import * as Schema from "effect/Schema";
6
+ import * as Result from "effect/Result";
7
+ import * as Data from "effect/Data";
8
+ export declare const utf8Encode: (text: string) => Uint8Array;
9
+ export declare const utf8Decode: (bytes: Uint8Array) => string;
10
+ export declare const toBase64: (bytes: Uint8Array) => string;
11
+ export declare const toBase64Url: (bytes: Uint8Array) => string;
12
+ export declare const toHex: (bytes: Uint8Array) => string;
13
+ export declare const fromBase64: (text: string) => Uint8Array | undefined;
14
+ export declare const fromBase64Url: (text: string) => Uint8Array | undefined;
15
+ export declare const fromHex: (text: string) => Uint8Array | undefined;
16
+ export declare const concatBytes: (...parts: ReadonlyArray<Uint8Array>) => Uint8Array;
17
+ /** Copies into a fresh ArrayBuffer-backed array, which WebCrypto's typings require. */
18
+ export declare const toBufferSource: (bytes: Uint8Array) => Uint8Array<ArrayBuffer>;
19
+ export declare const randomBytes: (length: number) => Uint8Array;
20
+ export declare const sha256: (data: Uint8Array | string) => Promise<Uint8Array>;
21
+ export declare const sha256Hex: (data: Uint8Array | string) => Promise<string>;
22
+ /** First 8 hex characters of the secret's SHA-256: safe to show, enough to tell secrets apart. */
23
+ export declare const fingerprint: (secret: string | Uint8Array) => Promise<string>;
24
+ export declare const importHmacKey: (algorithm: HashAlgorithm, key: Uint8Array) => Promise<CryptoKey>;
25
+ export declare const hmac: (algorithm: HashAlgorithm, key: Uint8Array, data: Uint8Array) => Promise<Uint8Array>;
26
+ /** Compares two byte arrays in time that depends only on their lengths. */
27
+ export declare const timingSafeEqual: (a: Uint8Array, b: Uint8Array) => boolean;
28
+ /**
29
+ * Compares two secrets by their SHA-256, so neither the content nor the length
30
+ * of the expected value leaks through timing. Used for tokens (§7.1).
31
+ */
32
+ export declare const secretsEqual: (provided: string, expected: string) => Promise<boolean>;
33
+ declare const KeyringError_base: Schema.Class<KeyringError, Schema.TaggedStruct<"KeyringError", {
34
+ readonly message: Schema.String;
35
+ }>, import("effect/Cause").YieldableError>;
36
+ /** Raised for a malformed `MANIFOLD_ENCRYPTION_KEYS`. Never carries key material. */
37
+ export declare class KeyringError extends KeyringError_base {}
38
+ declare const SecretBoxError_base: Schema.Class<SecretBoxError, Schema.TaggedStruct<"SecretBoxError", {
39
+ readonly reason: Schema.Literals<readonly ["malformed", "unknown_key", "decrypt_failed"]>;
40
+ readonly keyId: Schema.optionalKey<Schema.String>;
41
+ }>, import("effect/Cause").YieldableError>;
42
+ /** Raised when a sealed secret cannot be opened. Never carries the ciphertext or plaintext. */
43
+ export declare class SecretBoxError extends SecretBoxError_base {
44
+ get message(): string;
45
+ }
46
+ export interface EncryptionKey {
47
+ readonly id: string;
48
+ readonly key: CryptoKey;
49
+ }
50
+ export interface Keyring {
51
+ /** Encrypts new ciphertexts. */
52
+ readonly current: EncryptionKey;
53
+ /** Every key, by id, tried on decrypt. */
54
+ readonly keys: ReadonlyMap<string, EncryptionKey>;
55
+ }
56
+ /**
57
+ * Parses `"k2:<base64>,k1:<base64>"`. The first key is the current one. Each
58
+ * key must decode to exactly 32 bytes.
59
+ */
60
+ export declare const parseKeyring: (spec: string) => Promise<Keyring>;
61
+ export type SecretKind = "source" | "relay";
62
+ /** The associated data bound into each ciphertext: `"{kind}:{id}:{field}"`. */
63
+ export declare const secretAad: (kind: SecretKind, id: string, field: string) => string;
64
+ /** Seals `plaintext` as `v1.<keyId>.<nonce b64url>.<ciphertext b64url>`. */
65
+ export declare const sealSecret: (keyring: Keyring, plaintext: string, aad: string) => Promise<string>;
66
+ /** The key id a sealed secret was encrypted with, or `undefined` if malformed. */
67
+ export declare const sealedKeyId: (sealed: string) => string | undefined;
68
+ /** True when the secret was sealed with a key other than the current one. */
69
+ export declare const needsReseal: (keyring: Keyring, sealed: string) => boolean;
70
+ export declare const openSecret: (keyring: Keyring, sealed: string, aad: string) => Promise<string>;
71
+ /** Re-encrypts with the current key; returns the input unchanged when it already uses it. */
72
+ export declare const resealSecret: (keyring: Keyring, sealed: string, aad: string) => Promise<string>;
73
+ /** Seals a JSON value (for example a list of secrets) as one ciphertext. */
74
+ export declare const sealJson: (keyring: Keyring, value: Schema.Json, aad: string) => Promise<string>;
75
+ /** Opens a sealed JSON value and decodes it with `schema`. */
76
+ export declare const openJson: <A>(keyring: Keyring, sealed: string, aad: string, schema: Schema.Codec<A, unknown>) => Promise<A>;
77
+ declare const SecretBox_base: Context.ServiceClass<SecretBox, "manifold/core/SecretBox", {
78
+ readonly keyring: Keyring;
79
+ readonly seal: (plaintext: string, aad: string) => Effect.Effect<string>;
80
+ readonly open: (sealed: string, aad: string) => Effect.Effect<string, SecretBoxError>;
81
+ readonly reseal: (sealed: string, aad: string) => Effect.Effect<string, SecretBoxError>;
82
+ readonly needsReseal: (sealed: string) => boolean;
83
+ }>;
84
+ /** Effect service over a keyring, for runtimes that compose with Layers. */
85
+ export declare class SecretBox extends SecretBox_base {
86
+ static readonly fromKeyring: (keyring: Keyring) => SecretBox["Service"];
87
+ /** Builds the service from a `MANIFOLD_ENCRYPTION_KEYS` value. */
88
+ static readonly layer: (spec: string) => Layer.Layer<SecretBox, KeyringError>;
89
+ }
90
+ /**
91
+ * Event-type globs for route filters. `*` matches any run of characters
92
+ * (including `.`); everything else matches literally and case-sensitively.
93
+ * A request without an event type matches only the pattern `*`.
94
+ */
95
+ export declare const matchesGlob: (pattern: string, eventType: string | null | undefined) => boolean;
96
+ /** True when any of the route's patterns matches. */
97
+ export declare const matchesEventTypes: (patterns: ReadonlyArray<string>, eventType: string | null | undefined) => boolean;
98
+ export interface FilterableRoute {
99
+ readonly id: string;
100
+ readonly enabled: boolean;
101
+ readonly eventTypes: ReadonlyArray<string>;
102
+ }
103
+ /** The enabled routes whose filter matches; paused routes are included (their deliveries wait). */
104
+ export declare const matchingRoutes: <R extends FilterableRoute>(routes: ReadonlyArray<R>, eventType: string | null | undefined) => Array<R>;
105
+ /** Fetch `Headers`, or a plain record such as Node's `IncomingHttpHeaders`. */
106
+ export type HeadersLike = Headers | Readonly<Record<string, string | ReadonlyArray<string> | undefined>>;
107
+ /** Every header as `[lowercase name, value]`; repeated values joined with `, `. */
108
+ export declare const headerEntries: (headers: HeadersLike) => Array<[string, string]>;
109
+ export declare const getHeader: (headers: HeadersLike, name: string) => string | undefined;
110
+ /** Lowercase header names, sorted. What a rejection record keeps (§5.4). */
111
+ export declare const headerNames: (headers: HeadersLike) => Array<string>;
112
+ /** Always stored as `[redacted:<fingerprint>]`. */
113
+ export declare const ALWAYS_REDACTED: ReadonlyArray<string>;
114
+ export declare const redactedValue: (value: string) => Promise<string>;
115
+ /**
116
+ * The headers to store for a request: lowercase names, credentials and the
117
+ * listed headers replaced by `[redacted:<fingerprint>]`.
118
+ */
119
+ export declare const redactForStorage: (headers: HeadersLike, redact?: ReadonlyArray<string>) => Promise<Record<string, string>>;
120
+ /** Response headers redacted on attempt records. */
121
+ export declare const REDACTED_RESPONSE_HEADERS: ReadonlyArray<string>;
122
+ export declare const redactResponseHeaders: (headers: HeadersLike) => Record<string, string>;
123
+ export declare const HOP_BY_HOP_HEADERS: ReadonlyArray<string>;
124
+ /** The Standard Webhooks headers manifold sets on signed attempts. */
125
+ export declare const STANDARD_WEBHOOK_HEADERS: ReadonlyArray<string>;
126
+ /** True when an inbound header is never forwarded to a relay. */
127
+ export declare const isDroppedOnForward: (name: string) => boolean;
128
+ /**
129
+ * True when a relay's configured extra header may not be set, because
130
+ * manifold or the HTTP layer owns it.
131
+ */
132
+ export declare const isReservedRelayHeader: (name: string) => boolean;
133
+ export interface ForwardMeta {
134
+ readonly requestId: string;
135
+ readonly deliveryId: string;
136
+ readonly attempt: number;
137
+ readonly source: string;
138
+ readonly eventType: string | null;
139
+ readonly replay: boolean;
140
+ }
141
+ export interface RelayHeadersInput {
142
+ /** The request's headers as stored. */
143
+ readonly requestHeaders: Readonly<Record<string, string>>;
144
+ /** Headers never forwarded (the source's resolved `redactHeaders`). */
145
+ readonly redactHeaders?: ReadonlyArray<string>;
146
+ /** The relay's extra headers, plain and decrypted secret ones. */
147
+ readonly relayHeaders?: Readonly<Record<string, string>>;
148
+ readonly meta: ForwardMeta;
149
+ /** From `relaySignatureHeaders` when the relay has a signing secret. */
150
+ readonly signatureHeaders?: Readonly<Record<string, string>> | undefined;
151
+ }
152
+ /**
153
+ * The headers of an outbound attempt. Later layers win: inbound headers, then
154
+ * the relay's extra headers, then manifold's own and the signatures.
155
+ */
156
+ export declare const buildRelayHeaders: (input: RelayHeadersInput) => Record<string, string>;
157
+ /** Set on requests the CLI forwards to a local target, so an application can tell. */
158
+ export declare const LOCAL_HEADER = "manifold-local";
159
+ /** Methods sent without a body. */
160
+ export declare const BODYLESS_METHODS: ReadonlySet<string>;
161
+ /** The stored request, as the consumer's claim and the admin API both return it. */
162
+ export interface OutboundSource {
163
+ readonly id: string;
164
+ readonly sourceKey: string;
165
+ readonly receivedAt: number;
166
+ readonly method: string;
167
+ /** As stored (credentials already redacted). */
168
+ readonly headers: Readonly<Record<string, string>>;
169
+ readonly eventType: string | null;
170
+ readonly principal: Principal | null;
171
+ }
172
+ export interface OutboundInput {
173
+ readonly request: OutboundSource;
174
+ /** The raw body, byte for byte. */
175
+ readonly body: Uint8Array;
176
+ /** `dlv_…` for a relay, `lcl_…` for a local target. */
177
+ readonly deliveryId: string;
178
+ readonly attempt: number;
179
+ /** Sends `manifold-replay: true` and `replay: true` in the signed context. */
180
+ readonly replay: boolean;
181
+ /** Headers never forwarded (the source's resolved `redactHeaders`). */
182
+ readonly redactHeaders: ReadonlyArray<string>;
183
+ /** The relay's extra headers (plain and decrypted secret ones), or the CLI's `--header` values. */
184
+ readonly extraHeaders?: Readonly<Record<string, string>>;
185
+ /** Signs with these secrets (current first) at this time; omitted when the target has no signing secret. */
186
+ readonly signing?: {
187
+ readonly secrets: ReadonlyArray<string>;
188
+ /** Epoch seconds. */
189
+ readonly timestamp: number;
190
+ };
191
+ /** Adds `manifold-local: true`. */
192
+ readonly local?: boolean;
193
+ }
194
+ export interface OutboundRequest {
195
+ /** Upper case. */
196
+ readonly method: string;
197
+ readonly headers: Record<string, string>;
198
+ /** `undefined` for `GET` and `HEAD`. */
199
+ readonly body: Uint8Array | undefined;
200
+ }
201
+ export declare const buildOutboundRequest: (input: OutboundInput) => Promise<OutboundRequest>;
202
+ /** Matches a header value stored as `[redacted:<fingerprint>]` (§7.4). */
203
+ export declare const REDACTED_VALUE_PATTERN: RegExp;
204
+ /**
205
+ * The names of stored headers whose value was redacted at ingest. A client
206
+ * that cannot read the source's `redactHeaders` (a listen token may not read
207
+ * the source config) uses this instead: the stored set is the same, except
208
+ * for a list changed after the request was stored.
209
+ */
210
+ export declare const redactedHeaderNames: (headers: Readonly<Record<string, string>>) => Array<string>;
211
+ export declare const PRESETS: Readonly<Record<PresetId, Preset>>;
212
+ export declare const PRESET_LIST: ReadonlyArray<Preset>;
213
+ export declare const getPreset: (id: PresetId) => Preset;
214
+ /**
215
+ * Merges a source's verify override over a preset template. An override with
216
+ * a different `type` replaces the template; otherwise fields are merged
217
+ * shallowly. The result is decoded with `VerifySpec` (defaults applied).
218
+ */
219
+ export declare const resolveVerifySpec: (template: VerifyTemplate, override: VerifyOverride | undefined) => Result.Result<VerifySpec, string>;
220
+ /**
221
+ * A source's effective verification: preset plus overrides. Fails with a
222
+ * message when the merged spec is invalid, or when it is `none` without
223
+ * `allowUnverified`.
224
+ */
225
+ export declare const resolveSource: (source: Pick<SourceConfig, "preset" | "allowUnverified" | "verify" | "eventType" | "idempotencyKey" | "handshake" | "response" | "redactHeaders">) => Result.Result<ResolvedVerification, string>;
226
+ /** The raw body parsed as JSON, or `undefined` when it is not JSON. */
227
+ export declare const parseJsonBody: (rawBody: Uint8Array) => Schema.Json | undefined;
228
+ /** The value at a dot path. Numeric segments index arrays. */
229
+ export declare const getPath: (value: Schema.Json | undefined, path: string) => Schema.Json | undefined;
230
+ export interface ExtractInput {
231
+ readonly headers: HeadersLike;
232
+ /** The parsed JSON body (see `parseJsonBody`); `undefined` when not JSON. */
233
+ readonly json: Schema.Json | undefined;
234
+ }
235
+ /** Applies an extractor. Values longer than `LIMITS.extractedValueChars` are dropped. */
236
+ export declare const extract: (extractor: Extractor | null | undefined, input: ExtractInput) => string | null;
237
+ export interface Extracted {
238
+ readonly eventType: string | null;
239
+ readonly idempotencyKey: string | null;
240
+ }
241
+ export declare const extractAll: (resolved: Pick<ResolvedVerification, "eventType" | "idempotencyKey">, input: ExtractInput) => Extracted;
242
+ export interface HandshakeResponse {
243
+ readonly status: number;
244
+ readonly body: string;
245
+ readonly contentType: string;
246
+ }
247
+ /** The response to a handshake, or `undefined` when the request is not one. Run after verification. */
248
+ export declare const matchHandshake: (spec: HandshakeSpec | null | undefined, json: Schema.Json | undefined) => HandshakeResponse | undefined;
249
+ /** What happened to one attempt, as the consumer reports it. */
250
+ export declare const AttemptOutcome: Schema.Union<readonly [Schema.Struct<{
251
+ readonly type: Schema.Literal<"response">;
252
+ readonly status: Schema.Int;
253
+ /** The relay's `Retry-After` header, when present. */
254
+ readonly retryAfter: Schema.optionalKey<Schema.NullOr<Schema.String>>;
255
+ }>, Schema.Struct<{
256
+ readonly type: Schema.Literal<"network_error">;
257
+ readonly message: Schema.String;
258
+ }>, Schema.Struct<{
259
+ readonly type: Schema.Literal<"timeout">;
260
+ }>, Schema.Struct<{
261
+ readonly type: Schema.Literal<"blocked">;
262
+ readonly reason: Schema.String;
263
+ }>, Schema.Struct<{
264
+ readonly type: Schema.Literal<"lost">;
265
+ }>]>;
266
+ export type AttemptOutcome = typeof AttemptOutcome.Type;
267
+ export type OutcomeClass = "success" | "retryable" | "permanent";
268
+ /** 2xx succeeds; network errors, timeouts, lost attempts, 408, 429 and 5xx retry; anything else fails at once. */
269
+ export declare const classifyOutcome: (outcome: AttemptOutcome) => OutcomeClass;
270
+ /**
271
+ * The backoff before retry number `attempt + 1`, given `attempt` attempts so
272
+ * far (1-based). `random` returns a value in [0, 1).
273
+ */
274
+ export declare const backoffDelayMs: (policy: RetryPolicy, attempt: number, random?: () => number) => number;
275
+ /**
276
+ * Parses `Retry-After` (delta seconds or an HTTP date) into a delay in ms,
277
+ * capped at one hour. `undefined` when absent or malformed.
278
+ */
279
+ export declare const parseRetryAfter: (value: string | null | undefined, now: number) => number | undefined;
280
+ export type NextState = {
281
+ readonly status: "succeeded";
282
+ } | {
283
+ readonly status: "failed";
284
+ readonly reason: "permanent" | "attempts_exhausted";
285
+ } | {
286
+ readonly status: "pending";
287
+ readonly dueAt: number;
288
+ readonly delayMs: number;
289
+ };
290
+ export interface DecideInput {
291
+ readonly policy: RetryPolicy;
292
+ readonly outcome: AttemptOutcome;
293
+ /** Attempts made so far, including this one. */
294
+ readonly attemptCount: number;
295
+ /** The delivery's allowance (policy max, plus one per manual retry). */
296
+ readonly maxAttempts: number;
297
+ readonly now: number;
298
+ readonly random?: () => number;
299
+ }
300
+ /** The state a delivery moves to after an attempt finishes or is lost. */
301
+ export declare const decideNext: (input: DecideInput) => NextState;
302
+ /** The delivery status a `NextState` stores. */
303
+ export declare const nextStatus: (next: NextState) => DeliveryStatus;
304
+ /**
305
+ * The route's consecutive-failure count after an attempt: a success resets
306
+ * it, a failed attempt adds one, a lost attempt leaves it unchanged (the
307
+ * relay may have received it).
308
+ */
309
+ export declare const nextConsecutiveFailures: (previous: number, outcome: AttemptOutcome) => number;
310
+ /** True when the route should be paused with reason `consecutive_failures`. 0 disables auto-pause. */
311
+ export declare const shouldAutoPause: (consecutiveFailures: number, threshold: number) => boolean;
312
+ /** Statuses a manual retry accepts (§6.4); `dispatched` and `running` answer 409. */
313
+ export declare const RETRYABLE_BY_OPERATOR: ReadonlyArray<DeliveryStatus>;
314
+ export declare const CANCELLABLE: ReadonlyArray<DeliveryStatus>;
315
+ /** The parts of a verification a sender needs. */
316
+ export type SenderVerification = Pick<ResolvedVerification, "verify" | "eventType" | "idempotencyKey">;
317
+ /** The verification a preset gives a source with no overrides. */
318
+ export declare const presetVerification: (preset: PresetId) => SenderVerification;
319
+ /** Why a webhook could not be signed: no secret for a scheme that needs one, or a JWT scheme (which needs the sender's private key). */
320
+ export type SignFailure = "secret_required" | "jwt_unsupported";
321
+ export interface SignatureInput {
322
+ /** The raw body bytes, exactly as they will be sent. */
323
+ readonly body: Uint8Array;
324
+ /** Required for `hmac` and `token` verification. */
325
+ readonly secret?: string | undefined;
326
+ /** The ingest URL, for schemes that sign it. */
327
+ readonly url?: string | undefined;
328
+ /** Epoch ms; defaults to now. */
329
+ readonly now?: number | undefined;
330
+ }
331
+ /** The headers that authenticate `body` under `spec`, or why they cannot be made. */
332
+ export declare const signatureHeaders: (spec: VerifySpec, input: SignatureInput) => Promise<Result.Result<Record<string, string>, SignFailure>>;
333
+ export interface SignWebhookInput {
334
+ /** A preset id (its default verification) or a resolved verification, e.g. a source's `effective`. */
335
+ readonly preset: PresetId | SenderVerification;
336
+ /** A JSON value, serialized with `JSON.stringify`, or the raw bytes to send as is. */
337
+ readonly body: Schema.Json | Uint8Array;
338
+ /** The source's verification secret. Required unless the scheme is `none`. */
339
+ readonly secret?: string | undefined;
340
+ /** Extra headers, such as the event type header. Signature headers win. */
341
+ readonly headers?: Readonly<Record<string, string>> | undefined;
342
+ /** The ingest URL, for schemes that sign it. */
343
+ readonly url?: string | undefined;
344
+ /** Epoch ms; defaults to now. */
345
+ readonly now?: number | undefined;
346
+ }
347
+ export interface SignedWebhook {
348
+ readonly headers: Record<string, string>;
349
+ readonly body: Uint8Array;
350
+ }
351
+ /** Signs a webhook for a preset or verification. Throws when it cannot be signed (see `SignFailure`). */
352
+ export declare const signWebhook: (input: SignWebhookInput) => Promise<SignedWebhook>;
353
+ export interface SendWebhookInput extends Omit<SignWebhookInput, "url"> {
354
+ /** The source's ingest URL: `https://manifold.example.com/in/{key}`. */
355
+ readonly url: string | URL;
356
+ /** A `fetch` implementation; defaults to the global one. */
357
+ readonly fetch?: typeof globalThis.fetch;
358
+ }
359
+ /** Signs a webhook and POSTs it to an ingest URL. A `202` means Manifold stored it. */
360
+ export declare const sendWebhook: (input: SendWebhookInput) => Promise<Response>;
361
+ export declare const SIGNING_SECRET_PREFIX = "whsec_";
362
+ /** A new relay signing secret: `whsec_` and 32 random bytes in base64. */
363
+ export declare const generateSigningSecret: () => string;
364
+ /** The HMAC key of a `whsec_…` secret (a bare base64 secret is accepted too). */
365
+ export declare const signingKeyBytes: (secret: string) => Uint8Array | undefined;
366
+ /**
367
+ * What manifold verified about a request, passed to relays in `manifold-context`.
368
+ * `deliveryId` is a `dlv_` id from a relay, or an `lcl_` id when the
369
+ * `manifold` CLI forwards to a local target (docs/LOCAL-RELAY.md §4.2).
370
+ */
371
+ export declare const SignedContext: Schema.Struct<{
372
+ readonly requestId: Schema.String;
373
+ readonly deliveryId: Schema.Union<readonly [Schema.String, Schema.String]>;
374
+ readonly source: Schema.String;
375
+ readonly eventType: Schema.NullOr<Schema.String>;
376
+ readonly receivedAt: Schema.Int;
377
+ readonly replay: Schema.Boolean;
378
+ readonly principal: Schema.NullOr<Schema.Struct<{
379
+ readonly kind: Schema.Literal<"jwt">;
380
+ readonly iss: Schema.String;
381
+ readonly sub: Schema.NullOr<Schema.String>;
382
+ readonly email: Schema.NullOr<Schema.String>;
383
+ readonly aud: Schema.NullOr<Schema.String>;
384
+ }>>;
385
+ }>;
386
+ export type SignedContext = typeof SignedContext.Type;
387
+ export declare const encodeContext: (context: SignedContext) => string;
388
+ export declare const decodeContext: (text: string) => SignedContext | undefined;
389
+ export interface StandardWebhookSignInput {
390
+ readonly id: string;
391
+ /** Epoch seconds. */
392
+ readonly timestamp: number;
393
+ readonly body: Uint8Array;
394
+ /** Current secret first; the previous one during a rotation. */
395
+ readonly secrets: ReadonlyArray<string>;
396
+ }
397
+ export declare const signStandardWebhook: (input: StandardWebhookSignInput) => Promise<Record<string, string>>;
398
+ export interface RelaySignInput {
399
+ readonly context: SignedContext;
400
+ /** Epoch seconds. */
401
+ readonly timestamp: number;
402
+ readonly body: Uint8Array;
403
+ readonly secrets: ReadonlyArray<string>;
404
+ }
405
+ /** All five signature headers for one attempt. Pass them to `buildRelayHeaders`. */
406
+ export declare const relaySignatureHeaders: (input: RelaySignInput) => Promise<Record<string, string>>;
407
+ export type RelayVerifyFailure = "missing_headers" | "malformed" | "timestamp_out_of_tolerance" | "bad_signature" | "context_mismatch";
408
+ export interface RelayVerifyOptions {
409
+ readonly headers: HeadersLike;
410
+ readonly body: Uint8Array;
411
+ /** The relay's signing secret(s). During a rotation pass both. */
412
+ readonly secrets: ReadonlyArray<string>;
413
+ /** Epoch ms. Default `Date.now()`. */
414
+ readonly now?: number;
415
+ /** Allowed clock skew either way. Default 300. */
416
+ readonly toleranceSeconds?: number;
417
+ }
418
+ export type StandardWebhookVerifyResult = {
419
+ readonly ok: true;
420
+ readonly id: string;
421
+ readonly timestamp: number;
422
+ } | {
423
+ readonly ok: false;
424
+ readonly reason: RelayVerifyFailure;
425
+ };
426
+ export type RelayVerifyResult = {
427
+ readonly ok: true;
428
+ readonly context: SignedContext;
429
+ readonly timestamp: number;
430
+ } | {
431
+ readonly ok: false;
432
+ readonly reason: RelayVerifyFailure;
433
+ };
434
+ /** Verifies the Standard Webhooks headers (what any Standard Webhooks library does). */
435
+ export declare const verifyStandardWebhook: (options: RelayVerifyOptions) => Promise<StandardWebhookVerifyResult>;
436
+ /**
437
+ * Verifies manifold's signed context and returns it, so a relay can trust
438
+ * who manifold verified (`context.principal`), not only the body. Relays
439
+ * should still dedupe on `context.deliveryId`.
440
+ */
441
+ export declare const verifyRelayRequest: (options: RelayVerifyOptions) => Promise<RelayVerifyResult>;
442
+ /**
443
+ * Relay URL checks (§7.2), as a pure function. Run when a relay is saved and
444
+ * before every attempt. Hostname tricks that resolve to private addresses are
445
+ * handled by the `global_fetch_strictly_public` flag, not here.
446
+ */
447
+ export interface RelayUrlOptions {
448
+ /** `MANIFOLD_ALLOW_INSECURE_RELAYS`: allows `http` and private/local hosts. Local development only. */
449
+ readonly allowInsecure?: boolean | undefined;
450
+ /** manifold's own hosts (`host` with port, e.g. `manifold.example.com`). A relay may not target them. */
451
+ readonly selfHosts?: ReadonlyArray<string> | undefined;
452
+ /** `MANIFOLD_RELAY_HOST_ALLOWLIST`: when non-empty, the host must equal or end in `.{suffix}`. */
453
+ readonly hostAllowlist?: ReadonlyArray<string> | undefined;
454
+ }
455
+ export type RelayUrlRejection = "invalid_url" | "insecure_scheme" | "credentials_in_url" | "private_address" | "local_name" | "self_host" | "not_allowlisted";
456
+ export type RelayUrlCheck = {
457
+ readonly ok: true;
458
+ readonly url: URL;
459
+ } | {
460
+ readonly ok: false;
461
+ readonly reason: RelayUrlRejection;
462
+ readonly message: string;
463
+ };
464
+ /** Parses `"a.com, b.com"` into normalized suffixes. */
465
+ export declare const parseHostAllowlist: (value: string | undefined) => Array<string>;
466
+ export declare const hostMatchesSuffix: (hostname: string, suffix: string) => boolean;
467
+ /** True for IPv4 addresses that are not publicly routable. */
468
+ export declare const isNonPublicIpv4: ([a, b, c]: readonly [number, number, number, number]) => boolean;
469
+ /** True for IPv6 addresses that are not publicly routable, including mapped private IPv4. */
470
+ export declare const isNonPublicIpv6: (groups: ReadonlyArray<number>) => boolean;
471
+ /** Checks a relay URL. Returns the parsed URL when it may be used. */
472
+ export declare const checkRelayUrl: (input: string, options?: RelayUrlOptions) => RelayUrlCheck;
473
+ export declare const Jwk: Schema.Struct<{
474
+ readonly kty: Schema.String;
475
+ readonly kid: Schema.optionalKey<Schema.String>;
476
+ readonly alg: Schema.optionalKey<Schema.String>;
477
+ readonly use: Schema.optionalKey<Schema.String>;
478
+ readonly n: Schema.optionalKey<Schema.String>;
479
+ readonly e: Schema.optionalKey<Schema.String>;
480
+ readonly crv: Schema.optionalKey<Schema.String>;
481
+ readonly x: Schema.optionalKey<Schema.String>;
482
+ readonly y: Schema.optionalKey<Schema.String>;
483
+ }>;
484
+ export type Jwk = typeof Jwk.Type;
485
+ export declare const Jwks: Schema.Struct<{
486
+ readonly keys: Schema.$Array<Schema.Struct<{
487
+ readonly kty: Schema.String;
488
+ readonly kid: Schema.optionalKey<Schema.String>;
489
+ readonly alg: Schema.optionalKey<Schema.String>;
490
+ readonly use: Schema.optionalKey<Schema.String>;
491
+ readonly n: Schema.optionalKey<Schema.String>;
492
+ readonly e: Schema.optionalKey<Schema.String>;
493
+ readonly crv: Schema.optionalKey<Schema.String>;
494
+ readonly x: Schema.optionalKey<Schema.String>;
495
+ readonly y: Schema.optionalKey<Schema.String>;
496
+ }>>;
497
+ }>;
498
+ export type Jwks = typeof Jwks.Type;
499
+ /**
500
+ * Returns the key set at `url`. `refresh: true` asks for a fresh copy (after
501
+ * an unknown `kid`, the issuer may have rotated keys).
502
+ */
503
+ export type JwksFetcher = (url: string, options: {
504
+ readonly refresh: boolean;
505
+ }) => Promise<Jwks>;
506
+ export interface JwksCacheOptions {
507
+ readonly fetch?: typeof globalThis.fetch;
508
+ /** Default 10 minutes. */
509
+ readonly ttlMs?: number;
510
+ /** A refresh is skipped when the cached copy is younger than this. Default 30 s. */
511
+ readonly minRefreshMs?: number;
512
+ readonly now?: () => number;
513
+ }
514
+ /** A per-isolate cached JWKS fetcher backed by `fetch`. */
515
+ export declare const makeJwksCache: (options?: JwksCacheOptions) => JwksFetcher;
516
+ declare const JwksCache_base: Context.ServiceClass<JwksCache, "manifold/JwksCache", JwksFetcher>;
517
+ /** The isolate's JWKS fetcher. `JwksCache.layer` is a `makeJwksCache()` over the global `fetch`. */
518
+ export declare class JwksCache extends JwksCache_base {
519
+ static readonly layer: Layer.Layer<JwksCache, never, never>;
520
+ }
521
+ /**
522
+ * JWKS URLs accepted without operator action. `*` matches one DNS label.
523
+ * Operators add more with the `extra` argument of `isAllowedJwksUrl`.
524
+ */
525
+ export declare const DEFAULT_JWKS_URLS: ReadonlyArray<string>;
526
+ export declare const GOOGLE_JWKS_URL = "https://www.googleapis.com/oauth2/v3/certs";
527
+ /** The Cloudflare Access JWKS for a team domain such as `myteam.cloudflareaccess.com`. */
528
+ export declare const accessJwksUrl: (teamDomain: string) => string;
529
+ export declare const isAllowedJwksUrl: (url: string, extra?: ReadonlyArray<string>) => boolean;
530
+ export interface JwtVerifyInput {
531
+ readonly spec: JwtVerify;
532
+ readonly headers: HeadersLike;
533
+ /** Epoch ms. */
534
+ readonly now: number;
535
+ readonly fetchJwks?: JwksFetcher | undefined;
536
+ }
537
+ /** Verifies a compact JWS token string against `spec`. */
538
+ export declare const verifyJwtToken: (token: string, spec: JwtVerify, now: number, fetchJwks: JwksFetcher | undefined) => Promise<VerifyResult>;
539
+ export declare const verifyJwt: (input: JwtVerifyInput) => Promise<VerifyResult>;
540
+ export interface VerifyInput {
541
+ readonly spec: VerifySpec;
542
+ /** Plaintext secrets; a signature is valid if any of them matches. */
543
+ readonly secrets: ReadonlyArray<string>;
544
+ readonly headers: HeadersLike;
545
+ readonly rawBody: Uint8Array;
546
+ /** Current time, epoch ms. */
547
+ readonly now: number;
548
+ /** The full request URL, for templates using `{url}`. */
549
+ readonly url?: string | undefined;
550
+ /** Required for `jwt`. Use `makeJwksCache` for a cached `fetch`-backed one. */
551
+ readonly fetchJwks?: JwksFetcher | undefined;
552
+ /** The source's `allowUnverified`; `none` is refused without it. */
553
+ readonly allowUnverified?: boolean | undefined;
554
+ }
555
+ export type VerifyResult = Data.TaggedEnum<{
556
+ Verified: {
557
+ readonly principal: Principal | null;
558
+ /** The signed timestamp, epoch seconds, when the verifier has one. */
559
+ readonly timestamp: number | null;
560
+ /** The signed message id, when the verifier has one. */
561
+ readonly id: string | null;
562
+ /** Index into `secrets` of the secret that matched. */
563
+ readonly secretIndex: number | null;
564
+ };
565
+ Rejected: {
566
+ readonly reason: RejectionReason;
567
+ /** A short explanation. Never contains secrets, signatures or tokens. */
568
+ readonly detail: string;
569
+ };
570
+ }>;
571
+ export type Verified = Data.TaggedEnum.Value<VerifyResult, "Verified">;
572
+ export type Rejected = Data.TaggedEnum.Value<VerifyResult, "Rejected">;
573
+ export declare const VerifyResult: Data.TaggedEnum.Constructor<{
574
+ readonly _tag: "Rejected";
575
+ readonly reason: RejectionReason;
576
+ readonly detail: string;
577
+ } | {
578
+ readonly _tag: "Verified";
579
+ readonly principal: Principal | null;
580
+ readonly timestamp: number | null;
581
+ readonly id: string | null;
582
+ readonly secretIndex: number | null;
583
+ }>;
584
+ export declare const verified: (fields?: Partial<Omit<Verified, "_tag">>) => Verified;
585
+ export declare const rejected: (reason: RejectionReason, detail: string) => Rejected;
586
+ /** HMAC key bytes for a secret, or `undefined` when it does not decode. */
587
+ export declare const decodeHmacSecret: (encoding: HmacVerify["secretEncoding"], secret: string) => Uint8Array | undefined;
588
+ export interface SignedParts {
589
+ readonly body: Uint8Array;
590
+ /** Epoch seconds. */
591
+ readonly timestamp?: number | undefined;
592
+ readonly id?: string | undefined;
593
+ readonly url?: string | undefined;
594
+ }
595
+ /** The bytes a template signs: the template's text with `{body}` replaced by the raw body. */
596
+ export declare const buildSignedPayload: (template: string, parts: SignedParts) => Uint8Array;
597
+ /** Splits a `kv-list` header (`t=1,v1=a,v1=b`) into entries. */
598
+ export declare const parseKvList: (value: string) => Array<[string, string]>;
599
+ /** The encoded signatures carried by a signature header, per the spec's format. */
600
+ export declare const extractSignatures: (spec: HmacVerify, value: string) => Array<string>;
601
+ export interface HmacVerifyInput {
602
+ readonly spec: HmacVerify;
603
+ readonly secrets: ReadonlyArray<string>;
604
+ readonly headers: HeadersLike;
605
+ readonly rawBody: Uint8Array;
606
+ /** Epoch ms. */
607
+ readonly now: number;
608
+ readonly url?: string | undefined;
609
+ }
610
+ export declare const verifyHmac: (input: HmacVerifyInput) => Promise<VerifyResult>;
611
+ /** The encoded HMAC signature of `parts` under `spec`, as a sender would compute it. */
612
+ export declare const computeHmacSignature: (spec: HmacVerify, secret: string, parts: SignedParts) => Promise<string>;
613
+ /**
614
+ * The headers a sender would send for `parts` under `spec`, one signature
615
+ * per secret. Header-sourced timestamps and ids are included. For tests,
616
+ * fixtures and tooling.
617
+ */
618
+ export declare const signHmac: (spec: HmacVerify, secrets: ReadonlyArray<string>, parts: SignedParts) => Promise<Record<string, string>>;
619
+ /**
620
+ * Reads a credential from a header, stripping `{scheme} ` when a scheme is
621
+ * set. Returns `undefined` when absent or when the scheme does not match.
622
+ */
623
+ export declare const readCredential: (headers: HeadersLike, header: string, scheme: string | undefined) => string | undefined;
624
+ export interface TokenVerifyInput {
625
+ readonly spec: TokenVerify;
626
+ readonly secrets: ReadonlyArray<string>;
627
+ readonly headers: HeadersLike;
628
+ }
629
+ export declare const verifyToken: (input: TokenVerifyInput) => Promise<VerifyResult>;
630
+ export declare const verify: (input: VerifyInput) => Promise<VerifyResult>;
631
+ declare const VerificationError_base: Schema.Class<VerificationError, Schema.TaggedStruct<"VerificationError", {
632
+ readonly reason: Schema.Literals<readonly ["missing_signature", "malformed", "bad_signature", "missing_timestamp", "timestamp_out_of_tolerance", "missing_id", "no_secrets", "missing_token", "bad_token", "unverified_not_allowed", "jwt_missing", "jwt_malformed", "jwt_unsupported_alg", "jwt_unknown_kid", "jwt_bad_signature", "jwt_expired", "jwt_not_yet_valid", "jwt_bad_issuer", "jwt_bad_audience", "jwt_claim_mismatch", "jwks_unavailable"]>;
633
+ readonly detail: Schema.String;
634
+ }>, import("effect/Cause").YieldableError>;
635
+ /** A failed verification. `detail` never contains secrets, signatures or tokens. */
636
+ export declare class VerificationError extends VerificationError_base {
637
+ get message(): string;
638
+ }
639
+ export declare const verifyEffect: (input: VerifyInput) => Effect.Effect<Verified, VerificationError>;
640
+ export { ApplyChanges, ApplyResult, AttemptId, AttemptRecord, AttemptStatus, AuditAction, AuditRecord, AutoPauseThreshold, BodyPath, ClaimRequirement, ConfigDocument, ConfigDocumentInput, ConfigRelay, ConfigRoute, ConfigSource, Count, DedupeWindowSeconds, DeliveryDetail, DeliveryId, DeliveryRecord, DeliveryStatus, ERROR_STATUS, ErrorBody, ErrorCode, EventTypeGlob, Extractor, ExtractorPart, FINISHED_DELIVERY_STATUSES, Fingerprint, HandshakeSpec, HashAlgorithm, HeaderMap, HeaderName, HmacVerify, ID_PREFIXES, IdGenerator, IdGeneratorOptions, IdPrefix, IngestAck, IssuedSigningSecret, JsonChallengeHandshake, JwtAlgorithm, JwtVerify, KiB, LIMITS, LOCAL_ID_PREFIX, ListenTokenId, ListenTokenInfo, ListenerInfo, ListenerName, ListenerSessionId, ListenersSetting, LocalAttemptKind, LocalAttemptRecord, LocalId, MaxBodyBytes, MiB, Millis, NoneVerify, Page, PauseReason, PayloadTemplate, Preset, PresetId, PresetResponse, Principal, RejectionCounter, RejectionReason, RejectionRecord, Rejections, RelayConfig, RelayConfigInput, RelayId, RelayTimeoutMs, RelayView, RequestDetail, RequestId, RequestRecord, RequestStatus, ResolvedVerification, RetentionDays, RetryPolicy, Revision, RouteConfig, RouteConfigInput, RouteId, RouteState, RouteView, SecretEncoding, SecretHeaderInfo, SecretHeaders, SecretInfo, SecretValue, SignatureEncoding, SignatureFormat, SigningSecretInfo, SourceConfig, SourceConfigInput, SourceKey, SourceStats, SourceView, TIMINGS, TargetLabel, TokenVerify, Tolerance, ULID_PATTERN, ValueSource, VerifyOverride, VerifySpec, VerifyTemplate, VerifyType, idAt, idPattern, idTime, isId, isLocalId, makeIdGenerator, minIdAt, newId, newLocalId, relayConfigFields, routeConfigFields, sourceConfigFields };