@lostgradient/backchannel 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +62 -2
- package/dist/access-policy-metadata.d.ts +92 -0
- package/dist/access-policy-metadata.js +87 -0
- package/dist/asyncapi-channels.d.ts +46 -0
- package/dist/asyncapi-channels.js +399 -0
- package/dist/asyncapi.d.ts +40 -0
- package/dist/asyncapi.js +165 -0
- package/dist/authentication/api-key.d.ts +4 -0
- package/dist/authentication/api-key.js +114 -0
- package/dist/authentication/audit.d.ts +115 -0
- package/dist/authentication/audit.js +75 -0
- package/dist/authentication/credential-verifiers.d.ts +60 -0
- package/dist/authentication/credential-verifiers.js +102 -0
- package/dist/authentication/crypto.d.ts +7 -0
- package/dist/authentication/crypto.js +140 -0
- package/dist/authentication/index.d.ts +80 -0
- package/dist/authentication/index.js +212 -0
- package/dist/authentication/rate-limiter.d.ts +133 -0
- package/dist/authentication/rate-limiter.js +124 -0
- package/dist/authentication/redaction.d.ts +72 -0
- package/dist/authentication/redaction.js +118 -0
- package/dist/authentication/rotating-api-key-store.d.ts +127 -0
- package/dist/authentication/rotating-api-key-store.js +126 -0
- package/dist/authentication/types.d.ts +337 -0
- package/dist/authentication/types.js +26 -0
- package/dist/authentication.d.ts +1 -0
- package/dist/authentication.js +1 -0
- package/dist/authorization-scope.d.ts +109 -0
- package/dist/authorization-scope.js +144 -0
- package/dist/authorization.d.ts +55 -0
- package/dist/authorization.js +134 -0
- package/dist/bind-feed-lifetime.d.ts +45 -0
- package/dist/bind-feed-lifetime.js +55 -0
- package/dist/byte-arrays.d.ts +5 -0
- package/dist/byte-arrays.js +9 -0
- package/dist/client/catalog-client.d.ts +285 -0
- package/dist/client/catalog-client.js +74 -0
- package/dist/client/in-process-transport.d.ts +19 -0
- package/dist/client/in-process-transport.js +136 -0
- package/dist/client/index.d.ts +14 -0
- package/dist/client/index.js +14 -0
- package/dist/client/json-rpc-http-transport.d.ts +118 -0
- package/dist/client/json-rpc-http-transport.js +127 -0
- package/dist/client/server-sent-event-parser.d.ts +55 -0
- package/dist/client/server-sent-event-parser.js +78 -0
- package/dist/client/sse-subscription-transport.d.ts +72 -0
- package/dist/client/sse-subscription-transport.js +224 -0
- package/dist/client/subscription-client.d.ts +122 -0
- package/dist/client/subscription-client.js +28 -0
- package/dist/connection-lease.d.ts +10 -0
- package/dist/connection-lease.js +8 -0
- package/dist/discovery-filter.d.ts +13 -0
- package/dist/discovery-filter.js +16 -0
- package/dist/discovery-info.d.ts +94 -0
- package/dist/discovery-info.js +38 -0
- package/dist/event-selector.d.ts +7 -0
- package/dist/event-selector.js +7 -0
- package/dist/fault-code.d.ts +84 -0
- package/dist/fault-code.js +114 -0
- package/dist/fault-remediation.d.ts +30 -0
- package/dist/fault-remediation.js +52 -0
- package/dist/fault-to-http.d.ts +11 -0
- package/dist/fault-to-http.js +13 -0
- package/dist/fault-to-json-rpc.d.ts +53 -0
- package/dist/fault-to-json-rpc.js +143 -0
- package/dist/fault-wire-safety.d.ts +45 -0
- package/dist/fault-wire-safety.js +72 -0
- package/dist/generator.d.ts +9 -0
- package/dist/generator.js +9 -0
- package/dist/handler/auth-context-principal.d.ts +37 -0
- package/dist/handler/auth-context-principal.js +67 -0
- package/dist/handler/authentication-responses.d.ts +23 -0
- package/dist/handler/authentication-responses.js +34 -0
- package/dist/handler/json-responses.d.ts +15 -0
- package/dist/handler/json-responses.js +32 -0
- package/dist/handler/operation-handler-authentication.d.ts +64 -0
- package/dist/handler/operation-handler-authentication.js +58 -0
- package/dist/handler/operation-handler-discovery.d.ts +29 -0
- package/dist/handler/operation-handler-discovery.js +55 -0
- package/dist/handler/operation-handler-mounts.d.ts +100 -0
- package/dist/handler/operation-handler-mounts.js +134 -0
- package/dist/handler/operation-handler-subscription.d.ts +34 -0
- package/dist/handler/operation-handler-subscription.js +112 -0
- package/dist/handler/operation-handler.d.ts +162 -0
- package/dist/handler/operation-handler.js +236 -0
- package/dist/handler/workspace-release.d.ts +6 -0
- package/dist/handler/workspace-release.js +75 -0
- package/dist/in-memory-replay-live-backend.d.ts +47 -0
- package/dist/in-memory-replay-live-backend.js +129 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +30 -0
- package/dist/internal/cryptography/encryption.d.ts +108 -0
- package/dist/internal/cryptography/encryption.js +241 -0
- package/dist/internal/cryptography/hash.d.ts +72 -0
- package/dist/internal/cryptography/hash.js +233 -0
- package/dist/internal/cryptography/index.d.ts +4 -0
- package/dist/internal/cryptography/index.js +2 -0
- package/dist/internals.d.ts +58 -0
- package/dist/internals.js +54 -0
- package/dist/json-rpc-dispatch.d.ts +88 -0
- package/dist/json-rpc-dispatch.js +154 -0
- package/dist/json-rpc-framing.d.ts +42 -0
- package/dist/json-rpc-framing.js +50 -0
- package/dist/json-rpc-http.d.ts +36 -0
- package/dist/json-rpc-http.js +191 -0
- package/dist/json-rpc-parse.d.ts +69 -0
- package/dist/json-rpc-parse.js +206 -0
- package/dist/json-rpc-protocol.d.ts +76 -0
- package/dist/json-rpc-protocol.js +54 -0
- package/dist/json-rpc-session-runtime.d.ts +55 -0
- package/dist/json-rpc-session-runtime.js +111 -0
- package/dist/json-rpc-websocket-subscription-pump.d.ts +9 -0
- package/dist/json-rpc-websocket-subscription-pump.js +46 -0
- package/dist/json-rpc-websocket-subscriptions.d.ts +10 -0
- package/dist/json-rpc-websocket-subscriptions.js +33 -0
- package/dist/json-rpc-websocket-types.d.ts +34 -0
- package/dist/json-rpc-websocket-types.js +1 -0
- package/dist/json-rpc-websocket-validation.d.ts +45 -0
- package/dist/json-rpc-websocket-validation.js +154 -0
- package/dist/json-rpc-websocket.d.ts +20 -0
- package/dist/json-rpc-websocket.js +363 -0
- package/dist/json-schema-utilities.d.ts +5 -0
- package/dist/json-schema-utilities.js +17 -0
- package/dist/mcp-discovery-names.d.ts +11 -0
- package/dist/mcp-discovery-names.js +11 -0
- package/dist/openapi-canonical-json.d.ts +10 -0
- package/dist/openapi-canonical-json.js +23 -0
- package/dist/openapi-error-responses.d.ts +15 -0
- package/dist/openapi-error-responses.js +104 -0
- package/dist/openapi-schemas.d.ts +17 -0
- package/dist/openapi-schemas.js +94 -0
- package/dist/openapi.d.ts +60 -0
- package/dist/openapi.js +351 -0
- package/dist/openrpc-document-schema.d.ts +255 -0
- package/dist/openrpc-document-schema.js +84 -0
- package/dist/openrpc-errors.d.ts +93 -0
- package/dist/openrpc-errors.js +134 -0
- package/dist/openrpc.d.ts +66 -0
- package/dist/openrpc.js +260 -0
- package/dist/operation-catalog/behavior-types.d.ts +34 -0
- package/dist/operation-catalog/behavior-types.js +1 -0
- package/dist/operation-catalog/behavior-validation.d.ts +3 -0
- package/dist/operation-catalog/behavior-validation.js +298 -0
- package/dist/operation-catalog/dispatch-allowlist.d.ts +4 -0
- package/dist/operation-catalog/dispatch-allowlist.js +7 -0
- package/dist/operation-catalog/dispatch-preparation.d.ts +24 -0
- package/dist/operation-catalog/dispatch-preparation.js +49 -0
- package/dist/operation-catalog/index.d.ts +19 -0
- package/dist/operation-catalog/index.js +17 -0
- package/dist/operation-catalog/operation-dispatch.d.ts +14 -0
- package/dist/operation-catalog/operation-dispatch.js +115 -0
- package/dist/operation-catalog/operation-interceptors.d.ts +15 -0
- package/dist/operation-catalog/operation-interceptors.js +1 -0
- package/dist/operation-catalog/operation-metadata.d.ts +5 -0
- package/dist/operation-catalog/operation-metadata.js +104 -0
- package/dist/operation-catalog/pipeline-helpers.d.ts +70 -0
- package/dist/operation-catalog/pipeline-helpers.js +242 -0
- package/dist/operation-catalog/pipeline-stages.d.ts +23 -0
- package/dist/operation-catalog/pipeline-stages.js +226 -0
- package/dist/operation-catalog/pipeline.d.ts +7 -0
- package/dist/operation-catalog/pipeline.js +33 -0
- package/dist/operation-catalog/registry.d.ts +17 -0
- package/dist/operation-catalog/registry.js +132 -0
- package/dist/operation-catalog/stream-pipeline.d.ts +37 -0
- package/dist/operation-catalog/stream-pipeline.js +129 -0
- package/dist/operation-catalog/subscription-lifecycle.d.ts +6 -0
- package/dist/operation-catalog/subscription-lifecycle.js +27 -0
- package/dist/operation-catalog/types.d.ts +392 -0
- package/dist/operation-catalog/types.js +40 -0
- package/dist/operation-catalog/universal-faults.d.ts +11 -0
- package/dist/operation-catalog/universal-faults.js +15 -0
- package/dist/operation-catalog-snapshot.d.ts +215 -0
- package/dist/operation-catalog-snapshot.js +128 -0
- package/dist/operation-catalog.d.ts +1 -0
- package/dist/operation-catalog.js +1 -0
- package/dist/operation-description-audit.d.ts +44 -0
- package/dist/operation-description-audit.js +90 -0
- package/dist/operation-fault-helpers.d.ts +21 -0
- package/dist/operation-fault-helpers.js +32 -0
- package/dist/operation-fault.d.ts +245 -0
- package/dist/operation-fault.js +235 -0
- package/dist/operation-registry.d.ts +46 -0
- package/dist/operation-registry.js +46 -0
- package/dist/operations/closable-iterable.d.ts +23 -0
- package/dist/operations/closable-iterable.js +51 -0
- package/dist/operations/get-principal.d.ts +106 -0
- package/dist/operations/get-principal.js +107 -0
- package/dist/operations/sse-stream.d.ts +67 -0
- package/dist/operations/sse-stream.js +264 -0
- package/dist/principal.d.ts +253 -0
- package/dist/principal.js +254 -0
- package/dist/replay-live-feed-internals.d.ts +47 -0
- package/dist/replay-live-feed-internals.js +215 -0
- package/dist/replay-live-feed-types.d.ts +66 -0
- package/dist/replay-live-feed-types.js +7 -0
- package/dist/replay-live-feed.d.ts +49 -0
- package/dist/replay-live-feed.js +126 -0
- package/dist/rest-binding.d.ts +215 -0
- package/dist/rest-binding.js +95 -0
- package/dist/rest-body.d.ts +17 -0
- package/dist/rest-body.js +95 -0
- package/dist/route-model.d.ts +305 -0
- package/dist/route-model.js +320 -0
- package/dist/runtime/cors.d.ts +161 -0
- package/dist/runtime/cors.js +265 -0
- package/dist/scripts/generate-operation-client.d.ts +186 -0
- package/dist/scripts/generate-operation-client.js +561 -0
- package/dist/scripts/operation-behaviors.d.ts +3 -0
- package/dist/scripts/operation-behaviors.js +16 -0
- package/dist/scripts/operation-client-aliases.d.ts +32 -0
- package/dist/scripts/operation-client-aliases.js +255 -0
- package/dist/scripts/operation-client-domains.d.ts +21 -0
- package/dist/scripts/operation-client-domains.js +74 -0
- package/dist/scripts/operation-client-schema.d.ts +46 -0
- package/dist/scripts/operation-client-schema.js +310 -0
- package/dist/scripts/operation-client-svelte.d.ts +3 -0
- package/dist/scripts/operation-client-svelte.js +61 -0
- package/dist/sequence-cursor.d.ts +46 -0
- package/dist/sequence-cursor.js +62 -0
- package/dist/sse-error-payload-schema.d.ts +12 -0
- package/dist/sse-error-payload-schema.js +33 -0
- package/dist/stdio-session.d.ts +71 -0
- package/dist/stdio-session.js +347 -0
- package/dist/zod-json-schema.d.ts +22 -0
- package/dist/zod-json-schema.js +49 -0
- package/package.json +38 -3
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A `ReplayLiveFeedBackend` that keeps its log in memory.
|
|
3
|
+
*
|
|
4
|
+
* This is the live-only half of the feed's two shapes. `createReplayLiveFeed`
|
|
5
|
+
* is generic over its backend, so a feed built on this one supports replay,
|
|
6
|
+
* cursors, late joins, and filtering exactly as a durable feed does — for as
|
|
7
|
+
* long as the process lives. Swapping in a persisted backend later changes
|
|
8
|
+
* this file and nothing above it: not the feed, not a subscription operation,
|
|
9
|
+
* not a client.
|
|
10
|
+
*
|
|
11
|
+
* WHAT IT COSTS TO CHOOSE THIS FIRST. Events are lost on restart, and a
|
|
12
|
+
* client that reconnects after the process died receives a gap and can
|
|
13
|
+
* continue from the new log, but cannot recover lost events. `maxEvents`
|
|
14
|
+
* bounds the log so a long-lived producer cannot exhaust memory; once it is
|
|
15
|
+
* reached the oldest envelopes are dropped and a reconnect also sees a gap.
|
|
16
|
+
*
|
|
17
|
+
* Distinct from `in-memory-event-feed-backend.test-support.ts`, which
|
|
18
|
+
* implements the workflow-specific `WorkflowEventFeedBackend` (bucketed by
|
|
19
|
+
* workflow and selector) and is a test helper. This one is generic, carries
|
|
20
|
+
* no domain keys, and is production code.
|
|
21
|
+
*
|
|
22
|
+
* @module server/in-memory-replay-live-backend
|
|
23
|
+
*/
|
|
24
|
+
const INCARNATION_PATTERN = /^([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}):(-1|\d+)$/i;
|
|
25
|
+
/** How many envelopes an in-memory log retains before dropping its oldest. */
|
|
26
|
+
const DEFAULT_MAX_EVENTS = 10_000;
|
|
27
|
+
/** Creates an {@link InMemoryReplayLiveBackend} that keeps at most `maxEvents` envelopes and signals a gap to a cursor from an earlier incarnation. */
|
|
28
|
+
export function createInMemoryReplayLiveBackend(options = {}) {
|
|
29
|
+
const maxEvents = options.maxEvents ?? DEFAULT_MAX_EVENTS;
|
|
30
|
+
const incarnation = crypto.randomUUID();
|
|
31
|
+
const log = [];
|
|
32
|
+
const listeners = new Set();
|
|
33
|
+
const decode = (cursor) => {
|
|
34
|
+
if (cursor === '-1')
|
|
35
|
+
return { sequence: -1 };
|
|
36
|
+
const structured = INCARNATION_PATTERN.exec(cursor);
|
|
37
|
+
if (structured !== null) {
|
|
38
|
+
const sequence = Number(structured[2]);
|
|
39
|
+
if (!Number.isSafeInteger(sequence))
|
|
40
|
+
return 'invalid';
|
|
41
|
+
return structured[1] === incarnation ? { sequence } : 'gap';
|
|
42
|
+
}
|
|
43
|
+
if (/^\d+$/.test(cursor) && Number.isSafeInteger(Number(cursor)))
|
|
44
|
+
return 'gap';
|
|
45
|
+
return 'invalid';
|
|
46
|
+
};
|
|
47
|
+
const retentionGap = (replayOptions, first, decoded) => log.length > 0 &&
|
|
48
|
+
first > 0 &&
|
|
49
|
+
replayOptions.afterSequence < first - 1 &&
|
|
50
|
+
decoded !== 'gap' &&
|
|
51
|
+
decoded !== 'invalid';
|
|
52
|
+
return {
|
|
53
|
+
async *replay(replayOptions) {
|
|
54
|
+
// Snapshotted before yielding: `append` may run between yields, and a
|
|
55
|
+
// consumer replaying history must not be handed live events out of the
|
|
56
|
+
// same pass — the feed layer is what joins replay to live.
|
|
57
|
+
const snapshot = [...log];
|
|
58
|
+
const firstRetainedSequence = snapshot[0]?.sequence ?? 0;
|
|
59
|
+
const requested = replayOptions.requestedCursor;
|
|
60
|
+
const decoded = requested === undefined ? { sequence: replayOptions.afterSequence } : decode(requested);
|
|
61
|
+
if (options.createGapEnvelope !== undefined &&
|
|
62
|
+
retentionGap(replayOptions, firstRetainedSequence, decoded)) {
|
|
63
|
+
yield options.createGapEnvelope({
|
|
64
|
+
requestedCursor: requested ?? String(replayOptions.afterSequence),
|
|
65
|
+
firstRetainedSequence,
|
|
66
|
+
continuationCursor: `${incarnation}:${firstRetainedSequence - 1}`,
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
for (const envelope of snapshot) {
|
|
70
|
+
if (envelope.sequence > replayOptions.afterSequence)
|
|
71
|
+
yield envelope;
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
async snapshotTailSequence() {
|
|
75
|
+
return log.at(-1)?.sequence ?? -1;
|
|
76
|
+
},
|
|
77
|
+
decodeCursor(cursor) {
|
|
78
|
+
return decode(cursor);
|
|
79
|
+
},
|
|
80
|
+
encodeCursor(sequence) {
|
|
81
|
+
if (!Number.isSafeInteger(sequence) || sequence < -1)
|
|
82
|
+
throw new RangeError('Invalid sequence');
|
|
83
|
+
return `${incarnation}:${sequence}`;
|
|
84
|
+
},
|
|
85
|
+
async snapshotFirstRetainedSequence() {
|
|
86
|
+
return log[0]?.sequence ?? 0;
|
|
87
|
+
},
|
|
88
|
+
...(options.createGapEnvelope === undefined
|
|
89
|
+
? {}
|
|
90
|
+
: {
|
|
91
|
+
createGapEnvelope: ({ requestedCursor, firstRetainedSequence, continuationCursor }) => options.createGapEnvelope({
|
|
92
|
+
requestedCursor,
|
|
93
|
+
firstRetainedSequence,
|
|
94
|
+
continuationCursor,
|
|
95
|
+
}),
|
|
96
|
+
}),
|
|
97
|
+
subscribeLive(listener) {
|
|
98
|
+
listeners.add(listener);
|
|
99
|
+
return () => {
|
|
100
|
+
listeners.delete(listener);
|
|
101
|
+
};
|
|
102
|
+
},
|
|
103
|
+
append(envelope) {
|
|
104
|
+
log.push(envelope);
|
|
105
|
+
// Bounded rather than unbounded: an agent run emits events per step, and
|
|
106
|
+
// a feed nobody drains would otherwise grow for the process's lifetime.
|
|
107
|
+
if (log.length > maxEvents)
|
|
108
|
+
log.splice(0, log.length - maxEvents);
|
|
109
|
+
// Copied before iteration: a listener that unsubscribes itself while
|
|
110
|
+
// the set is being walked would otherwise skip the next one.
|
|
111
|
+
for (const listener of Array.from(listeners)) {
|
|
112
|
+
try {
|
|
113
|
+
listener(envelope);
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
// A listener that throws must not corrupt the producer or stop
|
|
117
|
+
// delivery to the listeners after it.
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
},
|
|
121
|
+
get size() {
|
|
122
|
+
return log.length;
|
|
123
|
+
},
|
|
124
|
+
dispose() {
|
|
125
|
+
listeners.clear();
|
|
126
|
+
log.length = 0;
|
|
127
|
+
},
|
|
128
|
+
};
|
|
129
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @lostgradient/backchannel
|
|
3
|
+
*
|
|
4
|
+
* The public surface of the operation layer.
|
|
5
|
+
*/
|
|
6
|
+
export { defaultAuthAuditSink, type AuthAuditEvent, type AuthAuditSink, } from "./authentication/audit.js";
|
|
7
|
+
export { createApiKeyVerifier, createAuthenticator, createJwtVerifier, createMutualTlsVerifier, validateAuthConfig, type CreateAuthenticatorOptions, type CredentialVerification, type CredentialVerifier, } from "./authentication/index.js";
|
|
8
|
+
export { createRateLimiter, validateRateLimitConfig, type RateLimitConfig, type RateLimitDecision, type RateLimitStore, type RateLimiter, } from "./authentication/rate-limiter.js";
|
|
9
|
+
export { isSensitiveHeader, redactCredential, redactHeaders } from "./authentication/redaction.js";
|
|
10
|
+
export { createRotatingApiKeyStore, type ApiKeyRegistration, type ApiKeyStore, type RotatingApiKeyStore, } from "./authentication/rotating-api-key-store.js";
|
|
11
|
+
export type { AuthConfig, AuthMethod, AuthResult, Authenticator, JWTAlgorithm, JWTConfig, JWTPayload, MTLSConfig, } from "./authentication/types.js";
|
|
12
|
+
export { PACKAGE_AUTHORIZATION_SCOPE_PATTERN, createScopeVocabulary, isAuthorizationScope, isPackageAuthorizationScope, type AuthorizationScope, type PackageAuthorizationScope, type ScopeVocabulary, } from "./authorization-scope.js";
|
|
13
|
+
export { bindFeedLifetime } from "./bind-feed-lifetime.js";
|
|
14
|
+
export type { DiscoveryInfo } from "./discovery-info.js";
|
|
15
|
+
export { isFaultCode, type FaultCode } from "./fault-code.js";
|
|
16
|
+
export { staleRevisionFault } from "./fault-wire-safety.js";
|
|
17
|
+
export { authContextToPrincipal, unauthenticatedLocalAuthContext, } from "./handler/auth-context-principal.js";
|
|
18
|
+
export { createOperationHandlerAuthenticator, type OperationHandlerAuthenticate, type OperationHandlerAuthenticator, type OperationHandlerAuthenticatorOptions, } from "./handler/operation-handler-authentication.js";
|
|
19
|
+
export type { OperationHandlerMount, OperationHandlerMountContext, OperationHandlerMountDispatchOptions, OperationHandlerMountOperation, } from "./handler/operation-handler-mounts.js";
|
|
20
|
+
export { createOperationHandler, type OperationHandler, type OperationHandlerOptions, } from "./handler/operation-handler.js";
|
|
21
|
+
export { guardWorkspaceResponse } from "./handler/workspace-release.js";
|
|
22
|
+
export { createInMemoryReplayLiveBackend, type InMemoryReplayLiveBackend, type InMemoryReplayLiveBackendOptions, } from "./in-memory-replay-live-backend.js";
|
|
23
|
+
export { dispatchJsonRpc, type DispatchJsonRpcContext, type DispatchJsonRpcResult, type JsonRpcSubscription, } from "./json-rpc-dispatch.js";
|
|
24
|
+
export { stringifyCatalogSnapshot, type CatalogAccessSnapshot, type CatalogOperationSnapshot, type CatalogRestBindingSnapshot, type CatalogSnapshot, } from "./operation-catalog-snapshot.js";
|
|
25
|
+
export { createOperationRegistry, type DispatchResult, type OperationRegistry, type OperationRegistryOptions, } from "./operation-catalog/index.js";
|
|
26
|
+
export { OPERATION_NAME_PATTERN, isValidOperationName, validateOperationName, type FaultPolicy, type OperationBehavior, type OperationContext, type OperationKind, type StreamOperationInvocation, type SubscriptionOperationInvocation, type TransportAvailability, type UnknownKeyPolicy, } from "./operation-catalog/types.js";
|
|
27
|
+
export { findUndescribedOperations } from "./operation-description-audit.js";
|
|
28
|
+
export type { OperationFault } from "./operation-fault.js";
|
|
29
|
+
export { defineOperation, type OperationDefinitionInput, type SchemaOperationDefinition, type StreamSchemaOperationDefinition, type SubscriptionSchemaOperationDefinition, type UnarySchemaOperationDefinition, } from "./operation-registry.js";
|
|
30
|
+
export { createReplayAwareClosableIterable, type ClosableAsyncIterable, type ReplayAwareClosableIterable, } from "./operations/closable-iterable.js";
|
|
31
|
+
export { createGetPrincipalOperation, type GetPrincipalOutput, } from "./operations/get-principal.js";
|
|
32
|
+
export { anonymousPrincipal, principalFromApiKey, principalFromJwtClaims, principalFromMutualTls, principalFromStdioLocal, principalFromUnauthenticatedLocal, type AuthenticatedPrincipal, type JwtClaims, type Principal, type UnauthenticatedPrincipal, type WorkspaceIdentity, } from "./principal.js";
|
|
33
|
+
export type { ReplayLiveFeed, ReplayLiveFeedBackend, ReplayLiveSubscribeOptions, } from "./replay-live-feed-types.js";
|
|
34
|
+
export { createReplayLiveFeed } from "./replay-live-feed.js";
|
|
35
|
+
export type { CorsOptions } from "./runtime/cors.js";
|
|
36
|
+
export { decodeCursor, encodeCursor, type Cursor, type SequencedEventEnvelope, } from "./sequence-cursor.js";
|
|
37
|
+
export type { OperationHostFactory, OperationInterceptor, OperationInterceptorContext, } from "./operation-catalog/operation-interceptors.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @lostgradient/backchannel
|
|
3
|
+
*
|
|
4
|
+
* The public surface of the operation layer.
|
|
5
|
+
*/
|
|
6
|
+
export { defaultAuthAuditSink, } from "./authentication/audit.js";
|
|
7
|
+
export { createApiKeyVerifier, createAuthenticator, createJwtVerifier, createMutualTlsVerifier, validateAuthConfig, } from "./authentication/index.js";
|
|
8
|
+
export { createRateLimiter, validateRateLimitConfig, } from "./authentication/rate-limiter.js";
|
|
9
|
+
export { isSensitiveHeader, redactCredential, redactHeaders } from "./authentication/redaction.js";
|
|
10
|
+
export { createRotatingApiKeyStore, } from "./authentication/rotating-api-key-store.js";
|
|
11
|
+
export { PACKAGE_AUTHORIZATION_SCOPE_PATTERN, createScopeVocabulary, isAuthorizationScope, isPackageAuthorizationScope, } from "./authorization-scope.js";
|
|
12
|
+
export { bindFeedLifetime } from "./bind-feed-lifetime.js";
|
|
13
|
+
export { isFaultCode } from "./fault-code.js";
|
|
14
|
+
export { staleRevisionFault } from "./fault-wire-safety.js";
|
|
15
|
+
export { authContextToPrincipal, unauthenticatedLocalAuthContext, } from "./handler/auth-context-principal.js";
|
|
16
|
+
export { createOperationHandlerAuthenticator, } from "./handler/operation-handler-authentication.js";
|
|
17
|
+
export { createOperationHandler, } from "./handler/operation-handler.js";
|
|
18
|
+
export { guardWorkspaceResponse } from "./handler/workspace-release.js";
|
|
19
|
+
export { createInMemoryReplayLiveBackend, } from "./in-memory-replay-live-backend.js";
|
|
20
|
+
export { dispatchJsonRpc, } from "./json-rpc-dispatch.js";
|
|
21
|
+
export { stringifyCatalogSnapshot, } from "./operation-catalog-snapshot.js";
|
|
22
|
+
export { createOperationRegistry, } from "./operation-catalog/index.js";
|
|
23
|
+
export { OPERATION_NAME_PATTERN, isValidOperationName, validateOperationName, } from "./operation-catalog/types.js";
|
|
24
|
+
export { findUndescribedOperations } from "./operation-description-audit.js";
|
|
25
|
+
export { defineOperation, } from "./operation-registry.js";
|
|
26
|
+
export { createReplayAwareClosableIterable, } from "./operations/closable-iterable.js";
|
|
27
|
+
export { createGetPrincipalOperation, } from "./operations/get-principal.js";
|
|
28
|
+
export { anonymousPrincipal, principalFromApiKey, principalFromJwtClaims, principalFromMutualTls, principalFromStdioLocal, principalFromUnauthenticatedLocal, } from "./principal.js";
|
|
29
|
+
export { createReplayLiveFeed } from "./replay-live-feed.js";
|
|
30
|
+
export { decodeCursor, encodeCursor, } from "./sequence-cursor.js";
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Authenticated encryption for stored secrets: AES-256-GCM through Web Crypto, with a keyring so a
|
|
3
|
+
* key can be rotated without losing values written under the old one.
|
|
4
|
+
*
|
|
5
|
+
* Design, in the order a reviewer is likely to ask:
|
|
6
|
+
*
|
|
7
|
+
* - **Fresh IV per encryption.** Every `encrypt` draws a new random 96-bit IV from
|
|
8
|
+
* `crypto.getRandomValues`; an IV is never derived, counted, or reused. With random 96-bit IVs the
|
|
9
|
+
* collision risk stays negligible up to roughly 2^32 encryptions under one key, so rotate a key
|
|
10
|
+
* long before it has sealed that many values.
|
|
11
|
+
* - **Key id.** A key's id is `hex(SHA-256("corvidae.cryptography.key-id.v1" || rawKey))`
|
|
12
|
+
* truncated to 12 bytes: 24 lowercase hexadecimal characters, which is a valid Bungalow secret-name
|
|
13
|
+
* suffix (`answer-encryption-key-<keyId>`). SHA-256 is preimage-resistant and the key is 256 bits of entropy, so the
|
|
14
|
+
* id reveals nothing usable about the key, and it is derived rather than stored, so a host can
|
|
15
|
+
* recompute the id (and the Bungalow secret name that embeds it) from the key alone.
|
|
16
|
+
* - **Additional authenticated data.** The version tag and the key id are bound into the GCM
|
|
17
|
+
* additional data, so rewriting either on a stored value fails authentication instead of silently
|
|
18
|
+
* selecting a different key or algorithm.
|
|
19
|
+
* - **Version.** Stored values carry `version: 1`. It is the only hook for a future algorithm
|
|
20
|
+
* change, and a stored value is long-lived, so the tag is cheap insurance on a persisted shape.
|
|
21
|
+
* - **Errors.** Every failure is a {@link CryptographyError} with a fixed message and a code. No
|
|
22
|
+
* message contains key material or plaintext, and WebCrypto's own error is never re-thrown.
|
|
23
|
+
*/
|
|
24
|
+
/** Why a cryptographic operation failed. */
|
|
25
|
+
export type CryptographyErrorCode =
|
|
26
|
+
/** The stored value names a key id that is not in the keyring. */
|
|
27
|
+
'secret-unavailable'
|
|
28
|
+
/** Authentication failed: the ciphertext, iv, key id, or version was altered, or the key is wrong. */
|
|
29
|
+
| 'authentication-failed'
|
|
30
|
+
/** The stored value is not shaped like output of {@link encrypt}. */
|
|
31
|
+
| 'malformed-secret'
|
|
32
|
+
/** The stored value carries a version this module does not understand. */
|
|
33
|
+
| 'unsupported-version'
|
|
34
|
+
/** An encoded key is not a valid base64url 256-bit key, or cannot be exported. */
|
|
35
|
+
| 'invalid-key'
|
|
36
|
+
/** Text that cannot round-trip: a string with a lone surrogate, or decrypted bytes that are not UTF-8. */
|
|
37
|
+
| 'invalid-text';
|
|
38
|
+
/** An error from this module. The message is fixed text and never contains key material or plaintext. */
|
|
39
|
+
export declare class CryptographyError extends Error {
|
|
40
|
+
/** The category of failure, for programmatic handling. */
|
|
41
|
+
readonly code: CryptographyErrorCode;
|
|
42
|
+
/** For `secret-unavailable`, the key id that the keyring could not supply. Not secret. */
|
|
43
|
+
readonly keyId: string | undefined;
|
|
44
|
+
/** Creates an error with a fixed message for the given code. */
|
|
45
|
+
constructor(code: CryptographyErrorCode, keyId?: string);
|
|
46
|
+
}
|
|
47
|
+
/** An AES-256-GCM key together with its derived id. Treat it as opaque; import or generate it. */
|
|
48
|
+
export type EncryptionKey = {
|
|
49
|
+
/** Identifier derived from the key (see the module notes); safe to store and log. */
|
|
50
|
+
readonly keyId: string;
|
|
51
|
+
/** The Web Crypto key. Imported keys are non-extractable unless requested otherwise. */
|
|
52
|
+
readonly cryptoKey: CryptoKey;
|
|
53
|
+
};
|
|
54
|
+
/** The current key plus retired keys, so values written before a rotation stay readable. */
|
|
55
|
+
export type Keyring = {
|
|
56
|
+
/** Encrypts new values; also decrypts values that name its id. */
|
|
57
|
+
readonly current: EncryptionKey;
|
|
58
|
+
/** Former keys, decrypt-only. Order does not matter. */
|
|
59
|
+
readonly retired?: readonly EncryptionKey[];
|
|
60
|
+
};
|
|
61
|
+
/** A stored encrypted value. All binary fields are base64url without padding. */
|
|
62
|
+
export type EncryptedValue = {
|
|
63
|
+
/** Shape version; always `1` today. */
|
|
64
|
+
readonly version: 1;
|
|
65
|
+
/** The ciphertext followed by the 128-bit authentication tag. */
|
|
66
|
+
readonly ciphertext: string;
|
|
67
|
+
/** The 96-bit initialization vector, unique to this encryption. */
|
|
68
|
+
readonly iv: string;
|
|
69
|
+
/** Id of the key that encrypted the value. */
|
|
70
|
+
readonly keyId: string;
|
|
71
|
+
};
|
|
72
|
+
/** Options for {@link importEncryptionKey}. */
|
|
73
|
+
export type ImportEncryptionKeyOptions = {
|
|
74
|
+
/** Allow {@link exportEncryptionKey} on the result. Defaults to `false`. */
|
|
75
|
+
readonly extractable?: boolean;
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* Generates a new random AES-256 key. The result is extractable so the host can persist it with
|
|
79
|
+
* {@link exportEncryptionKey}.
|
|
80
|
+
*/
|
|
81
|
+
export declare function generateEncryptionKey(): Promise<EncryptionKey>;
|
|
82
|
+
/**
|
|
83
|
+
* Imports a key previously produced by {@link exportEncryptionKey}: base64url of exactly 32 bytes.
|
|
84
|
+
* Throws `invalid-key` for anything else.
|
|
85
|
+
*/
|
|
86
|
+
export declare function importEncryptionKey(encoded: string, options?: ImportEncryptionKeyOptions): Promise<EncryptionKey>;
|
|
87
|
+
/**
|
|
88
|
+
* Exports a key as base64url of its 32 raw bytes, for storage as a secret. The result is key
|
|
89
|
+
* material: never log it. Throws `invalid-key` when the key was imported without `extractable`.
|
|
90
|
+
*/
|
|
91
|
+
export declare function exportEncryptionKey(key: EncryptionKey): Promise<string>;
|
|
92
|
+
/**
|
|
93
|
+
* Encrypts text (UTF-8) or bytes under `key` with a fresh random IV. The result is safe to persist
|
|
94
|
+
* as JSON.
|
|
95
|
+
*/
|
|
96
|
+
export declare function encrypt(plaintext: string | Uint8Array, key: EncryptionKey): Promise<EncryptedValue>;
|
|
97
|
+
/**
|
|
98
|
+
* Decrypts a value written by {@link encrypt} to bytes, using whichever keyring entry its `keyId`
|
|
99
|
+
* names. Throws a {@link CryptographyError}: `malformed-secret` or `unsupported-version` for a
|
|
100
|
+
* misshapen value, `secret-unavailable` when the keyring lacks the key, `authentication-failed` when
|
|
101
|
+
* any field was altered.
|
|
102
|
+
*/
|
|
103
|
+
export declare function decryptBytes(value: EncryptedValue, keyring: Keyring): Promise<Uint8Array>;
|
|
104
|
+
/**
|
|
105
|
+
* Like {@link decryptBytes}, then decodes the result as UTF-8, keeping a leading U+FEFF so the text
|
|
106
|
+
* round-trips exactly; throws `invalid-text` if the bytes are not UTF-8.
|
|
107
|
+
*/
|
|
108
|
+
export declare function decrypt(value: EncryptedValue, keyring: Keyring): Promise<string>;
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Authenticated encryption for stored secrets: AES-256-GCM through Web Crypto, with a keyring so a
|
|
3
|
+
* key can be rotated without losing values written under the old one.
|
|
4
|
+
*
|
|
5
|
+
* Design, in the order a reviewer is likely to ask:
|
|
6
|
+
*
|
|
7
|
+
* - **Fresh IV per encryption.** Every `encrypt` draws a new random 96-bit IV from
|
|
8
|
+
* `crypto.getRandomValues`; an IV is never derived, counted, or reused. With random 96-bit IVs the
|
|
9
|
+
* collision risk stays negligible up to roughly 2^32 encryptions under one key, so rotate a key
|
|
10
|
+
* long before it has sealed that many values.
|
|
11
|
+
* - **Key id.** A key's id is `hex(SHA-256("corvidae.cryptography.key-id.v1" || rawKey))`
|
|
12
|
+
* truncated to 12 bytes: 24 lowercase hexadecimal characters, which is a valid Bungalow secret-name
|
|
13
|
+
* suffix (`answer-encryption-key-<keyId>`). SHA-256 is preimage-resistant and the key is 256 bits of entropy, so the
|
|
14
|
+
* id reveals nothing usable about the key, and it is derived rather than stored, so a host can
|
|
15
|
+
* recompute the id (and the Bungalow secret name that embeds it) from the key alone.
|
|
16
|
+
* - **Additional authenticated data.** The version tag and the key id are bound into the GCM
|
|
17
|
+
* additional data, so rewriting either on a stored value fails authentication instead of silently
|
|
18
|
+
* selecting a different key or algorithm.
|
|
19
|
+
* - **Version.** Stored values carry `version: 1`. It is the only hook for a future algorithm
|
|
20
|
+
* change, and a stored value is long-lived, so the tag is cheap insurance on a persisted shape.
|
|
21
|
+
* - **Errors.** Every failure is a {@link CryptographyError} with a fixed message and a code. No
|
|
22
|
+
* message contains key material or plaintext, and WebCrypto's own error is never re-thrown.
|
|
23
|
+
*/
|
|
24
|
+
/** The only stored-value version this module reads and writes. */
|
|
25
|
+
const STORED_VERSION = 1;
|
|
26
|
+
const KEY_BYTES = 32;
|
|
27
|
+
const IV_BYTES = 12;
|
|
28
|
+
const TAG_BYTES = 16;
|
|
29
|
+
const KEY_ID_BYTES = 12;
|
|
30
|
+
const KEY_ID_DOMAIN = 'corvidae.cryptography.key-id.v1';
|
|
31
|
+
const ADDITIONAL_DATA_DOMAIN = 'corvidae.cryptography.aes-256-gcm';
|
|
32
|
+
/** An error from this module. The message is fixed text and never contains key material or plaintext. */
|
|
33
|
+
export class CryptographyError extends Error {
|
|
34
|
+
/** The category of failure, for programmatic handling. */
|
|
35
|
+
code;
|
|
36
|
+
/** For `secret-unavailable`, the key id that the keyring could not supply. Not secret. */
|
|
37
|
+
keyId;
|
|
38
|
+
/** Creates an error with a fixed message for the given code. */
|
|
39
|
+
constructor(code, keyId) {
|
|
40
|
+
super(messages[code]);
|
|
41
|
+
this.name = 'CryptographyError';
|
|
42
|
+
this.code = code;
|
|
43
|
+
this.keyId = keyId;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const messages = {
|
|
47
|
+
'secret-unavailable': 'The key that encrypted this value is not available.',
|
|
48
|
+
'authentication-failed': 'The encrypted value failed authentication.',
|
|
49
|
+
'malformed-secret': 'The encrypted value is malformed.',
|
|
50
|
+
'unsupported-version': 'The encrypted value uses an unsupported version.',
|
|
51
|
+
'invalid-key': 'The encryption key is invalid.',
|
|
52
|
+
'invalid-text': 'The decrypted value is not valid UTF-8 text.',
|
|
53
|
+
};
|
|
54
|
+
const textEncoder = new TextEncoder();
|
|
55
|
+
/** Base64url (RFC 4648 section 5) without padding. */
|
|
56
|
+
function encodeBase64Url(bytes) {
|
|
57
|
+
let binary = '';
|
|
58
|
+
for (const byte of bytes)
|
|
59
|
+
binary += String.fromCharCode(byte);
|
|
60
|
+
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');
|
|
61
|
+
}
|
|
62
|
+
/** Strict decoder: rejects anything that is not the canonical encoding of some byte string. */
|
|
63
|
+
function decodeBase64Url(encoded) {
|
|
64
|
+
if (typeof encoded !== 'string' || !/^[A-Za-z0-9_-]*$/.test(encoded))
|
|
65
|
+
return undefined;
|
|
66
|
+
if (encoded.length % 4 === 1)
|
|
67
|
+
return undefined;
|
|
68
|
+
try {
|
|
69
|
+
const binary = atob(encoded.replaceAll('-', '+').replaceAll('_', '/'));
|
|
70
|
+
const bytes = new Uint8Array(binary.length);
|
|
71
|
+
for (let index = 0; index < binary.length; index += 1)
|
|
72
|
+
bytes[index] = binary.charCodeAt(index);
|
|
73
|
+
// Reject non-canonical encodings (nonzero trailing bits) so one byte string has one encoding.
|
|
74
|
+
return encodeBase64Url(bytes) === encoded ? bytes : undefined;
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function toHex(bytes) {
|
|
81
|
+
let hex = '';
|
|
82
|
+
for (const byte of bytes)
|
|
83
|
+
hex += byte.toString(16).padStart(2, '0');
|
|
84
|
+
return hex;
|
|
85
|
+
}
|
|
86
|
+
async function deriveKeyId(rawKey) {
|
|
87
|
+
const domain = textEncoder.encode(KEY_ID_DOMAIN);
|
|
88
|
+
const input = new Uint8Array(domain.length + rawKey.length);
|
|
89
|
+
input.set(domain, 0);
|
|
90
|
+
input.set(rawKey, domain.length);
|
|
91
|
+
const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', input));
|
|
92
|
+
input.fill(0);
|
|
93
|
+
return toHex(digest.slice(0, KEY_ID_BYTES));
|
|
94
|
+
}
|
|
95
|
+
async function importRawKey(rawKey, extractable) {
|
|
96
|
+
try {
|
|
97
|
+
const keyId = await deriveKeyId(rawKey);
|
|
98
|
+
const cryptoKey = await crypto.subtle.importKey('raw', rawKey, 'AES-GCM', extractable, [
|
|
99
|
+
'encrypt',
|
|
100
|
+
'decrypt',
|
|
101
|
+
]);
|
|
102
|
+
return { keyId, cryptoKey };
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
throw new CryptographyError('invalid-key');
|
|
106
|
+
}
|
|
107
|
+
finally {
|
|
108
|
+
rawKey.fill(0);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Generates a new random AES-256 key. The result is extractable so the host can persist it with
|
|
113
|
+
* {@link exportEncryptionKey}.
|
|
114
|
+
*/
|
|
115
|
+
export async function generateEncryptionKey() {
|
|
116
|
+
const rawKey = new Uint8Array(KEY_BYTES);
|
|
117
|
+
crypto.getRandomValues(rawKey);
|
|
118
|
+
return importRawKey(rawKey, true);
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Imports a key previously produced by {@link exportEncryptionKey}: base64url of exactly 32 bytes.
|
|
122
|
+
* Throws `invalid-key` for anything else.
|
|
123
|
+
*/
|
|
124
|
+
export async function importEncryptionKey(encoded, options = {}) {
|
|
125
|
+
const decoded = decodeBase64Url(encoded);
|
|
126
|
+
if (decoded === undefined || decoded.length !== KEY_BYTES) {
|
|
127
|
+
throw new CryptographyError('invalid-key');
|
|
128
|
+
}
|
|
129
|
+
const rawKey = new Uint8Array(KEY_BYTES);
|
|
130
|
+
rawKey.set(decoded);
|
|
131
|
+
decoded.fill(0);
|
|
132
|
+
return importRawKey(rawKey, options.extractable === true);
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Exports a key as base64url of its 32 raw bytes, for storage as a secret. The result is key
|
|
136
|
+
* material: never log it. Throws `invalid-key` when the key was imported without `extractable`.
|
|
137
|
+
*/
|
|
138
|
+
export async function exportEncryptionKey(key) {
|
|
139
|
+
let raw;
|
|
140
|
+
try {
|
|
141
|
+
raw = new Uint8Array(await crypto.subtle.exportKey('raw', key.cryptoKey));
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
throw new CryptographyError('invalid-key');
|
|
145
|
+
}
|
|
146
|
+
const encoded = encodeBase64Url(raw);
|
|
147
|
+
raw.fill(0);
|
|
148
|
+
return encoded;
|
|
149
|
+
}
|
|
150
|
+
function additionalData(keyId) {
|
|
151
|
+
// Fields are separated by NUL; a key id is lowercase hex and so cannot contain one.
|
|
152
|
+
return textEncoder.encode(`${ADDITIONAL_DATA_DOMAIN}\0${STORED_VERSION}\0${keyId}`);
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Encrypts text (UTF-8) or bytes under `key` with a fresh random IV. The result is safe to persist
|
|
156
|
+
* as JSON.
|
|
157
|
+
*/
|
|
158
|
+
export async function encrypt(plaintext, key) {
|
|
159
|
+
if (typeof plaintext !== 'string' && !(plaintext instanceof Uint8Array)) {
|
|
160
|
+
throw new TypeError('encrypt expects a string or a Uint8Array.');
|
|
161
|
+
}
|
|
162
|
+
// Snapshot caller-owned inputs before the first await.
|
|
163
|
+
const keyId = key.keyId;
|
|
164
|
+
const cryptoKey = key.cryptoKey;
|
|
165
|
+
if (typeof plaintext === 'string' && !plaintext.isWellFormed()) {
|
|
166
|
+
// TextEncoder would silently replace a lone surrogate with U+FFFD and change the value.
|
|
167
|
+
throw new CryptographyError('invalid-text');
|
|
168
|
+
}
|
|
169
|
+
const data = typeof plaintext === 'string' ? textEncoder.encode(plaintext) : plaintext;
|
|
170
|
+
const iv = new Uint8Array(IV_BYTES);
|
|
171
|
+
crypto.getRandomValues(iv);
|
|
172
|
+
let sealed;
|
|
173
|
+
try {
|
|
174
|
+
sealed = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: additionalData(keyId), tagLength: TAG_BYTES * 8 }, cryptoKey, new Uint8Array(data));
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
throw new CryptographyError('invalid-key');
|
|
178
|
+
}
|
|
179
|
+
return {
|
|
180
|
+
version: STORED_VERSION,
|
|
181
|
+
ciphertext: encodeBase64Url(new Uint8Array(sealed)),
|
|
182
|
+
iv: encodeBase64Url(iv),
|
|
183
|
+
keyId,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
/** Finds a key by id in the keyring. Linear scan: a keyring holds a handful of keys. */
|
|
187
|
+
function findKey(keyring, keyId) {
|
|
188
|
+
if (keyring.current.keyId === keyId)
|
|
189
|
+
return keyring.current;
|
|
190
|
+
return keyring.retired?.find((candidate) => candidate.keyId === keyId);
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Decrypts a value written by {@link encrypt} to bytes, using whichever keyring entry its `keyId`
|
|
194
|
+
* names. Throws a {@link CryptographyError}: `malformed-secret` or `unsupported-version` for a
|
|
195
|
+
* misshapen value, `secret-unavailable` when the keyring lacks the key, `authentication-failed` when
|
|
196
|
+
* any field was altered.
|
|
197
|
+
*/
|
|
198
|
+
export async function decryptBytes(value, keyring) {
|
|
199
|
+
const candidate = value;
|
|
200
|
+
if (typeof candidate !== 'object' || candidate === null) {
|
|
201
|
+
throw new CryptographyError('malformed-secret');
|
|
202
|
+
}
|
|
203
|
+
const fields = candidate;
|
|
204
|
+
const version = Object.hasOwn(fields, 'version') ? fields['version'] : undefined;
|
|
205
|
+
if (version !== STORED_VERSION) {
|
|
206
|
+
throw new CryptographyError(typeof version === 'number' ? 'unsupported-version' : 'malformed-secret');
|
|
207
|
+
}
|
|
208
|
+
const keyId = Object.hasOwn(fields, 'keyId') ? fields['keyId'] : undefined;
|
|
209
|
+
const iv = decodeBase64Url(Object.hasOwn(fields, 'iv') ? fields['iv'] : undefined);
|
|
210
|
+
const sealed = decodeBase64Url(Object.hasOwn(fields, 'ciphertext') ? fields['ciphertext'] : undefined);
|
|
211
|
+
if (typeof keyId !== 'string' ||
|
|
212
|
+
iv === undefined ||
|
|
213
|
+
iv.length !== IV_BYTES ||
|
|
214
|
+
sealed === undefined ||
|
|
215
|
+
sealed.length < TAG_BYTES) {
|
|
216
|
+
throw new CryptographyError('malformed-secret');
|
|
217
|
+
}
|
|
218
|
+
const key = findKey(keyring, keyId);
|
|
219
|
+
if (key === undefined)
|
|
220
|
+
throw new CryptographyError('secret-unavailable', keyId);
|
|
221
|
+
try {
|
|
222
|
+
const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv, additionalData: additionalData(keyId), tagLength: TAG_BYTES * 8 }, key.cryptoKey, sealed);
|
|
223
|
+
return new Uint8Array(plain);
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
throw new CryptographyError('authentication-failed');
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Like {@link decryptBytes}, then decodes the result as UTF-8, keeping a leading U+FEFF so the text
|
|
231
|
+
* round-trips exactly; throws `invalid-text` if the bytes are not UTF-8.
|
|
232
|
+
*/
|
|
233
|
+
export async function decrypt(value, keyring) {
|
|
234
|
+
const bytes = await decryptBytes(value, keyring);
|
|
235
|
+
try {
|
|
236
|
+
return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
|
|
237
|
+
}
|
|
238
|
+
catch {
|
|
239
|
+
throw new CryptographyError('invalid-text');
|
|
240
|
+
}
|
|
241
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cross-platform cryptographic hashing utilities.
|
|
3
|
+
*
|
|
4
|
+
* - `sha256Hex` uses the Web Crypto API and works in all environments (browser, Node, Bun, Deno).
|
|
5
|
+
* - `sha256HexSync` is synchronous and works in Bun and in Node.js 20.16.0+ (20.x line) or 22.3.0+ (throws in browsers
|
|
6
|
+
* and in older Node.js, where `process.getBuiltinModule` does not exist — use the async `sha256Hex`
|
|
7
|
+
* there instead, or supply a `require`-based runtime override; see below).
|
|
8
|
+
* - `hmacSha256HexSync` signs text with HMAC-SHA-256 under the same Bun/Node 20.16.0+ (20.x) or 22.3.0+ requirement.
|
|
9
|
+
* - `timingSafeEqualHex` compares hex digests without leaking the first differing byte (same
|
|
10
|
+
* Bun/Node 20.16.0+ (20.x) or 22.3.0+ requirement as the other synchronous helpers).
|
|
11
|
+
* - `createIncrementalHash` returns a streaming hasher for accumulating data across multiple
|
|
12
|
+
* `.update()` calls (same Bun/Node 20.16.0+ (20.x) or 22.3.0+ requirement).
|
|
13
|
+
*
|
|
14
|
+
* The synchronous helpers read `node:crypto` via `process.getBuiltinModule` rather than a literal
|
|
15
|
+
* `require(...)` call, specifically so that bundling this package for a browser build never injects
|
|
16
|
+
* a `createRequire`/`node:module` shim (see AB-31). That trades away support for Node.js versions
|
|
17
|
+
* outside `^20.16.0 || >=22.3.0` for the synchronous path; a caller that must support older Node can
|
|
18
|
+
* still supply its own loader via the `corvidae.cryptography.hash.runtime` global override
|
|
19
|
+
* (see `getHashRuntimeOverride` below) — set `{ require: (specifier) => require(specifier) }` from
|
|
20
|
+
* a CommonJS entry point where a real `require` exists.
|
|
21
|
+
*/
|
|
22
|
+
/** Interface for an incremental (streaming) hash that accumulates data via `.update()`. */
|
|
23
|
+
export type IncrementalHash = {
|
|
24
|
+
/** Feed more data into the hash. */
|
|
25
|
+
update(data: string): void;
|
|
26
|
+
/** Finalize and return the hex digest. */
|
|
27
|
+
digest(): string;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Computes the SHA-256 hex digest of a string using the Web Crypto API.
|
|
31
|
+
* Works in all environments: browsers, Node.js, Bun, Deno.
|
|
32
|
+
*/
|
|
33
|
+
export declare function sha256Hex(text: string): Promise<string>;
|
|
34
|
+
/**
|
|
35
|
+
* Computes the SHA-256 hex digest of raw bytes using the Web Crypto API.
|
|
36
|
+
* Works in all environments: browsers, Node.js, Bun, Deno.
|
|
37
|
+
*
|
|
38
|
+
* Digesting bytes rather than a string is what lets a caller hash content it cannot decode —
|
|
39
|
+
* a bundled image or font, say — without first corrupting it through a lossy text round trip.
|
|
40
|
+
*/
|
|
41
|
+
export declare function sha256BytesHex(data: Uint8Array): Promise<string>;
|
|
42
|
+
/**
|
|
43
|
+
* Computes the SHA-256 hex digest of a string synchronously.
|
|
44
|
+
* Uses `node:crypto`, which Bun and Node.js both provide.
|
|
45
|
+
* Throws in browser environments where no synchronous crypto API is available.
|
|
46
|
+
*/
|
|
47
|
+
export declare function sha256HexSync(text: string): string;
|
|
48
|
+
/** Computes the SHA-256 hex digest of raw bytes synchronously. */
|
|
49
|
+
export declare function sha256BytesHexSync(data: Uint8Array): string;
|
|
50
|
+
/** Computes a SHA-256 digest in the base64url representation PKCE requires. */
|
|
51
|
+
export declare function sha256Base64UrlSync(text: string): string;
|
|
52
|
+
/**
|
|
53
|
+
* Computes an HMAC-SHA-256 hex signature synchronously.
|
|
54
|
+
* Uses `node:crypto`, which Bun and Node.js both provide.
|
|
55
|
+
* Throws in browser environments where no synchronous HMAC API is available.
|
|
56
|
+
*/
|
|
57
|
+
export declare function hmacSha256HexSync(secret: string, text: string): string;
|
|
58
|
+
/**
|
|
59
|
+
* Compares two hex strings with Node's timing-safe equality when available.
|
|
60
|
+
* Invalid hex strings and different-length values are never equal.
|
|
61
|
+
*/
|
|
62
|
+
export declare function timingSafeEqualHex(left: string, right: string): boolean;
|
|
63
|
+
/** Compares UTF-8 text with Node's timing-safe equality for equal-size inputs. */
|
|
64
|
+
export declare function timingSafeEqualText(left: string, right: string): boolean;
|
|
65
|
+
/**
|
|
66
|
+
* Creates an incremental (streaming) hash for accumulating data across multiple `.update()` calls.
|
|
67
|
+
* Uses `node:crypto`, which Bun and Node.js both provide.
|
|
68
|
+
* Throws in browser environments where no synchronous streaming crypto API is available.
|
|
69
|
+
*
|
|
70
|
+
* @param algorithm - Hash algorithm to use. Default: `'sha256'`.
|
|
71
|
+
*/
|
|
72
|
+
export declare function createIncrementalHash(algorithm?: string): IncrementalHash;
|