@fungi.computer/computer 0.14.8 → 0.15.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.
@@ -4,7 +4,12 @@ export type PublicGitRoute = Readonly<{
4
4
  /** `push` is GitHub receive-pack only, and never tried anonymously. */
5
5
  readonly access: "read" | "push";
6
6
  }>;
7
- export type ComputerEgressDecision = Readonly<{
7
+ export type ComputerEgressDecision =
8
+ /** The request presents one Vault reference; only its owner places a value. */
9
+ Readonly<{
10
+ kind: "vault";
11
+ reference: string;
12
+ }> | Readonly<{
8
13
  kind: "team-git";
9
14
  route: PublicGitRoute;
10
15
  }> | Readonly<{
@@ -15,7 +20,7 @@ export type ComputerEgressDecision = Readonly<{
15
20
  kind: "origin-git";
16
21
  }> | Readonly<{
17
22
  kind: "denied";
18
- reason: "origin" | "method" | "path";
23
+ reason: "origin" | "method" | "path" | "references";
19
24
  }>;
20
25
  /** An HTTPS URL with the default port and no userinfo or fragment. */
21
26
  export declare function egressHttpsUrl(url: URL): boolean;
@@ -32,7 +37,7 @@ export type OriginGitHost = Readonly<{
32
37
  route(request: Pick<Request, "method">, url: URL): object | null;
33
38
  }>;
34
39
  /** One owner for origin, method and route decisions at Computer egress. */
35
- export declare function decideComputerEgress(request: Pick<Request, "method">, url: URL, host?: OriginGitHost): ComputerEgressDecision;
40
+ export declare function decideComputerEgress(request: Pick<Request, "method" | "headers">, url: URL, host?: OriginGitHost): ComputerEgressDecision;
36
41
  /** Remove all caller credentials and forward only transport headers needed by
37
42
  * anonymous registries and Git smart HTTP. `body: "move"` hands the caller's
38
43
  * stream over once (a push, which never has an anonymous attempt). */
@@ -71,7 +76,7 @@ export type ComputerEgressEvent = Readonly<{
71
76
  event: "computer.egress";
72
77
  computerId: string;
73
78
  teamId: string | null;
74
- lane: "team-git" | "public" | "internal-git" | "origin-git" | "denied";
79
+ lane: "vault" | "team-git" | "public" | "internal-git" | "origin-git" | "denied";
75
80
  host: string;
76
81
  method: string;
77
82
  status: number;
@@ -87,3 +92,26 @@ export declare function computerEgressDenied(input: Omit<ComputerEgressEvent, "e
87
92
  * Shed sets as `http.<remote>.extraHeader`) travels; the gateway adds none.
88
93
  */
89
94
  export declare function originGitRequest(request: Request, url: URL): Request;
95
+ /** A Vault lane request as its owner receives it: plain data, sent by the owner. */
96
+ export type VaultRequestData = Readonly<{
97
+ url: string;
98
+ method: string;
99
+ headers: readonly (readonly [string, string])[];
100
+ body: ArrayBuffer | null;
101
+ }>;
102
+ /** The gateway status for an owner's refusal code; the code stays in the log. */
103
+ export declare function vaultRefusalStatus(code: string): number;
104
+ /**
105
+ * The guest's request without its reference. Every header that carries the
106
+ * reference (Basic decoded) and every query parameter that does is removed;
107
+ * the owner places the value at the secret's own placement. A reference in
108
+ * the path can be neither removed nor placed, so it is refused, as is a body
109
+ * above the owner's `bodyLimit`, read no further than that.
110
+ */
111
+ export declare function vaultRequestData(request: Request, url: URL, reference: string, bodyLimit: number): Promise<Readonly<{
112
+ kind: "ready";
113
+ data: VaultRequestData;
114
+ }> | Readonly<{
115
+ kind: "refused";
116
+ reason: "placement" | "too_large";
117
+ }>>;
@@ -3,9 +3,10 @@
3
3
  * and route each outbound request names. Every host's egress gateway decides
4
4
  * here and refuses with the same response; a host serves only the lanes it
5
5
  * offers (Hub: team, public and its own App Git; standalone Oyster: its own
6
- * origin's Git) and refuses every other decision.
6
+ * origin's Git; both: the Vault lane) and refuses every other decision.
7
7
  */
8
8
  import { z } from "zod";
9
+ import { vaultReferencesIn } from "./vault-references.js";
9
10
  const publicGitHosts = new Set(["github.com", "gitlab.com", "codeberg.org"]);
10
11
  const packageHosts = new Set([
11
12
  "registry.npmjs.org",
@@ -93,10 +94,45 @@ export function sameOriginHttps(url, origin) {
93
94
  configured.password === "" &&
94
95
  url.origin === configured.origin);
95
96
  }
97
+ /** The references one header carries, including inside a Basic credential. */
98
+ function headerReferences(name, value) {
99
+ const basic = /^Basic\s+([A-Za-z0-9+/=]+)$/iu.exec(value)?.[1];
100
+ const decoded = name.toLowerCase() === "authorization" && basic !== undefined
101
+ ? basicCredential(basic)
102
+ : "";
103
+ return [...vaultReferencesIn(value), ...vaultReferencesIn(decoded)];
104
+ }
105
+ /** A Basic credential's text; one that is not base64 decodes to nothing, and the raw value is still searched. */
106
+ function basicCredential(encoded) {
107
+ try {
108
+ return atob(encoded);
109
+ }
110
+ catch {
111
+ return "";
112
+ }
113
+ }
114
+ /** Every distinct Vault reference in a header value or the URL. */
115
+ function presentedVaultReferences(request, url) {
116
+ return [
117
+ ...new Set([
118
+ ...vaultReferencesIn(url.pathname),
119
+ ...vaultReferencesIn(url.search),
120
+ ...[...request.headers].flatMap(([name, value]) => headerReferences(name, value)),
121
+ ]),
122
+ ];
123
+ }
96
124
  /** One owner for origin, method and route decisions at Computer egress. */
97
125
  export function decideComputerEgress(request, url, host) {
98
126
  if (!egressHttpsUrl(url))
99
127
  return { kind: "denied", reason: "origin" };
128
+ // A reference goes to the Vault lane wherever it is sent: an unbound
129
+ // destination is the owner's refusal to record, never another lane's request.
130
+ const references = presentedVaultReferences(request, url);
131
+ const [reference] = references;
132
+ if (references.length > 1)
133
+ return { kind: "denied", reason: "references" };
134
+ if (reference !== undefined)
135
+ return { kind: "vault", reference };
100
136
  if (url.hostname === "git.team.internal" ||
101
137
  url.hostname === "build.team.internal")
102
138
  return { kind: "internal-git" };
@@ -238,3 +274,73 @@ export function originGitRequest(request, url) {
238
274
  Object.assign(init, { body: request.body, duplex: "half" });
239
275
  return new Request(url, init);
240
276
  }
277
+ /** The gateway status for an owner's refusal code; the code stays in the log. */
278
+ export function vaultRefusalStatus(code) {
279
+ switch (code) {
280
+ case "too_large":
281
+ return 413;
282
+ case "rate_limited":
283
+ return 429;
284
+ case "invalid_response":
285
+ return 502;
286
+ case "unavailable":
287
+ return 503;
288
+ default:
289
+ return 403;
290
+ }
291
+ }
292
+ /**
293
+ * The guest's request without its reference. Every header that carries the
294
+ * reference (Basic decoded) and every query parameter that does is removed;
295
+ * the owner places the value at the secret's own placement. A reference in
296
+ * the path can be neither removed nor placed, so it is refused, as is a body
297
+ * above the owner's `bodyLimit`, read no further than that.
298
+ */
299
+ export async function vaultRequestData(request, url, reference, bodyLimit) {
300
+ if (url.pathname.includes(reference))
301
+ return { kind: "refused", reason: "placement" };
302
+ const target = new URL(url);
303
+ // Collected first: deleting while iterating URLSearchParams skips entries.
304
+ const carriers = Array.from(target.searchParams).filter(([name, value]) => name.includes(reference) || value.includes(reference));
305
+ for (const [name] of carriers)
306
+ target.searchParams.delete(name);
307
+ const headers = [...request.headers].filter(([name, value]) => !headerReferences(name, value).includes(reference));
308
+ // A GET or HEAD carries no body to send, though the guest's stream may be open.
309
+ if (request.body === null ||
310
+ request.method === "GET" ||
311
+ request.method === "HEAD")
312
+ return {
313
+ kind: "ready",
314
+ data: { url: target.href, method: request.method, headers, body: null },
315
+ };
316
+ const chunks = [];
317
+ let size = 0;
318
+ const reader = request.body.getReader();
319
+ for (;;) {
320
+ const next = await reader.read();
321
+ if (next.done)
322
+ break;
323
+ const chunk = z.instanceof(Uint8Array).parse(next.value);
324
+ size += chunk.byteLength;
325
+ if (size > bodyLimit) {
326
+ await reader.cancel();
327
+ return { kind: "refused", reason: "too_large" };
328
+ }
329
+ chunks.push(chunk);
330
+ }
331
+ const body = new Uint8Array(size);
332
+ let offset = 0;
333
+ for (const chunk of chunks) {
334
+ body.set(chunk, offset);
335
+ offset += chunk.byteLength;
336
+ }
337
+ return {
338
+ kind: "ready",
339
+ data: {
340
+ url: target.href,
341
+ method: request.method,
342
+ headers,
343
+ body: body.buffer,
344
+ },
345
+ };
346
+ }
@@ -0,0 +1,2 @@
1
+ /** Report a Computer catch without printing exception or request data. */
2
+ export declare function reportCatchFailure(operation: string, cause: unknown): void;
@@ -0,0 +1,9 @@
1
+ import * as Redacted from "effect/Redacted";
2
+ /** Report a Computer catch without printing exception or request data. */
3
+ export function reportCatchFailure(operation, cause) {
4
+ console.error(JSON.stringify({
5
+ source: "computer",
6
+ operation,
7
+ failureKind: cause instanceof Error ? "Error" : "NonErrorThrown",
8
+ }), Redacted.make(cause));
9
+ }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export type { WorkspaceRuntimeResultOptions } from "@fungi.computer/cloudflare-computer";
2
2
  export { createLocalBackendReplayStore } from "./local-backend-replay.js";
3
+ import { type VaultGrantPort, type VaultReferenceAdmission } from "./vault-references.js";
3
4
  import { Workspace, WorkspaceProxy, WorkspaceServiceProxy, type WorkspaceStub, type WorkspaceRuntimeResultOptions } from "@fungi.computer/cloudflare-computer";
4
5
  import { type WorkerShellBackendOptions } from "@fungi.computer/cloudflare-computer/backends/worker-shell";
5
6
  import { type IWorkspaceContainerAPI } from "@fungi.computer/cloudflare-computer/backends/container";
@@ -169,6 +170,16 @@ export declare class ComputerDO extends ContainerComputer implements ComputerFil
169
170
  keepAwake(enabled?: boolean): Promise<boolean>;
170
171
  /** Ordinary Computers have no credential host; resource hosts override it. */
171
172
  protected executionHooks(): ComputerExecutionHostHooks | undefined;
173
+ /**
174
+ * The hooks that put an Agent command's Vault references in its
175
+ * environment, beside the host's own (see `withVaultExecution`).
176
+ */
177
+ protected vaultExecutionHooks(port: VaultGrantPort): ComputerExecutionHostHooks;
178
+ /**
179
+ * What a reference this Computer's gateway intercepted names, only while
180
+ * the command it was given to is actually live; otherwise nothing.
181
+ */
182
+ admitVaultReference(reference: string): Promise<VaultReferenceAdmission | null>;
172
183
  /**
173
184
  * Admission observes the actual native subscriber, never App completion,
174
185
  * output silence, an accepted signal or this isolate's warm state.
@@ -278,7 +289,7 @@ export declare class ComputerDO extends ContainerComputer implements ComputerFil
278
289
  * or the first available in the default order. Host-only `hosted` execution
279
290
  * excludes local backends, including an explicitly named local backend.
280
291
  */
281
- protected executeOperationAfterAcceptance(input: ComputerExecRequest, accept: () => void, kind: "exec" | "bash" | "hosted", budget?: ComputerExecutionBudget, signal?: AbortSignal, executionContext?: ComputerValue, resultOptions?: WorkspaceRuntimeResultOptions): Promise<ComputerOperationResult>;
292
+ protected executeOperationAfterAcceptance(input: ComputerExecRequest, accept: () => void, kind: "exec" | "bash" | "hosted", budget?: ComputerExecutionBudget, signal?: AbortSignal, requestedContext?: ComputerValue, resultOptions?: WorkspaceRuntimeResultOptions): Promise<ComputerOperationResult>;
282
293
  /**
283
294
  * Run one command on a routed backend. Owners admit and meter hosted
284
295
  * backends here; a member's own machine is neither reserved nor metered.
@@ -333,6 +344,7 @@ export { WorkspaceProxy, WorkspaceServiceProxy };
333
344
  export { computerName, learnComputerName } from "./computer-name.js";
334
345
  export { OnBoxVmContainerHost, OnBoxVmTimeoutError, onBoxVmPlacement, onBoxVmIngress, type OnBoxVmEnv, type OnBoxVmOperation, type OnBoxVmState, } from "./on-box-vm.js";
335
346
  export { computerContainerSleepAfterMs } from "./container-policy.js";
347
+ export { isVaultExecutionContext, vaultExecutionContext, withVaultExecution, type VaultGrantPort, type VaultHolder, type VaultReferenceAdmission, type VaultSecretGrant, type VaultSubject, } from "./vault-references.js";
336
348
  export * from "./computer-backends.js";
337
349
  export { LocalBackendOfflineError, localBackendAudience, localBackendDialPath, ownerLocalBackendDialPath, verifyLocalBackendDial, } from "./local-backend.js";
338
350
  /** Keep each native Workspace lease inside the operation that uses it. */
package/dist/index.js CHANGED
@@ -53,6 +53,7 @@ var __disposeResources = (this && this.__disposeResources) || (function (Suppres
53
53
  import { boundExecStream } from "./exec-output.js";
54
54
  export { createLocalBackendReplayStore } from "./local-backend-replay.js";
55
55
  import { computerInternetAccess } from "./internet-access.js";
56
+ import { createComputerVaultReferences, isVaultExecutionContext, vaultExecutionHooks, } from "./vault-references.js";
56
57
  import { computerName, learnComputerName, recordComputerName, } from "./computer-name.js";
57
58
  import { getWorkspace, SQLiteWorkspaceProvider, Workspace, WorkspaceProxy, WorkspaceServiceProxy, } from "@fungi.computer/cloudflare-computer";
58
59
  import { WorkerShellBackend, } from "@fungi.computer/cloudflare-computer/backends/worker-shell";
@@ -615,6 +616,7 @@ export class ComputerDO extends ContainerComputer {
615
616
  #operationRecord;
616
617
  #processRecord;
617
618
  #executionRecord;
619
+ #vaultReferenceRecord;
618
620
  #processStarts = new Map();
619
621
  #terminalSync;
620
622
  get #processes() {
@@ -629,6 +631,28 @@ export class ComputerDO extends ContainerComputer {
629
631
  executionHooks() {
630
632
  return undefined;
631
633
  }
634
+ get #vaultReferences() {
635
+ return (this.#vaultReferenceRecord ??= createComputerVaultReferences(this.state.storage.sql));
636
+ }
637
+ /**
638
+ * The hooks that put an Agent command's Vault references in its
639
+ * environment, beside the host's own (see `withVaultExecution`).
640
+ */
641
+ vaultExecutionHooks(port) {
642
+ return vaultExecutionHooks(this.#vaultReferences, port);
643
+ }
644
+ /**
645
+ * What a reference this Computer's gateway intercepted names, only while
646
+ * the command it was given to is actually live; otherwise nothing.
647
+ */
648
+ async admitVaultReference(reference) {
649
+ const admission = await this.#vaultReferences.find(reference);
650
+ if (admission === null)
651
+ return null;
652
+ return (await this.executionIsLive(admission.invocationId))
653
+ ? admission
654
+ : null;
655
+ }
632
656
  get #executions() {
633
657
  if (this.#executionRecord === undefined) {
634
658
  // Initialize the existing retention owners before their dependent table.
@@ -1140,11 +1164,18 @@ export class ComputerDO extends ContainerComputer {
1140
1164
  * or the first available in the default order. Host-only `hosted` execution
1141
1165
  * excludes local backends, including an explicitly named local backend.
1142
1166
  */
1143
- async executeOperationAfterAcceptance(input, accept, kind, budget = genericComputerExecutionBudget, signal, executionContext, resultOptions) {
1167
+ async executeOperationAfterAcceptance(input, accept, kind, budget = genericComputerExecutionBudget, signal, requestedContext, resultOptions) {
1144
1168
  const { requestId, ...command } = computerExecutionRequestSchema(budget).parse(input);
1145
1169
  const route = kind === "exec" && command.backend === undefined
1146
1170
  ? undefined
1147
1171
  : this.routeBackend(command.backend, kind === "hosted" ? "hosted" : "exec");
1172
+ // Only a hosted backend's gateway resolves Vault references: a member's
1173
+ // own machine runs the Agent's command as before, with none.
1174
+ const executionContext = requestedContext !== undefined &&
1175
+ isVaultExecutionContext(requestedContext) &&
1176
+ (route === undefined || this.hostedRoute(route.id) === undefined)
1177
+ ? undefined
1178
+ : requestedContext;
1148
1179
  if (executionContext !== undefined) {
1149
1180
  if (route === undefined)
1150
1181
  throw new Error("Host execution requires a hosted native backend");
@@ -1718,6 +1749,7 @@ export { WorkspaceProxy, WorkspaceServiceProxy };
1718
1749
  export { computerName, learnComputerName } from "./computer-name.js";
1719
1750
  export { OnBoxVmContainerHost, OnBoxVmTimeoutError, onBoxVmPlacement, onBoxVmIngress, } from "./on-box-vm.js";
1720
1751
  export { computerContainerSleepAfterMs } from "./container-policy.js";
1752
+ export { isVaultExecutionContext, vaultExecutionContext, withVaultExecution, } from "./vault-references.js";
1721
1753
  export * from "./computer-backends.js";
1722
1754
  export { LocalBackendOfflineError, localBackendAudience, localBackendDialPath, ownerLocalBackendDialPath, verifyLocalBackendDial, } from "./local-backend.js";
1723
1755
  /** Keep each native Workspace lease inside the operation that uses it. */
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Vault references: the only form in which a Vault secret enters a Computer.
3
+ *
4
+ * When a Computer opens an Agent command's native invocation, it asks the
5
+ * owner which secrets that Agent holds and puts one `fvr1.` reference per
6
+ * secret into that command's environment, under the secret's name. A
7
+ * reference is not the credential. It names the owner, the secret, the Agent
8
+ * and this command's invocation, and only this Computer's egress gateway resolves it,
9
+ * only while that invocation is live. The gateway then asks the owner to place
10
+ * the real value on a request to one of the secret's bound destinations. Only
11
+ * a reference's digest is stored, so a copy on another Computer, or after its
12
+ * command ended, names nothing.
13
+ *
14
+ * Apps hold no Vault power: the only subject a reference can name is an Agent.
15
+ */
16
+ import type { ComputerExecutionHostHooks, ComputerValue } from "@fungi.computer/computer-contract";
17
+ import type { WatchdogSqliteOwner } from "@fungi.computer/watchdog";
18
+ import { z } from "zod";
19
+ /** Every distinct reference written anywhere in `text`. */
20
+ export declare function vaultReferencesIn(text: string): readonly string[];
21
+ declare const subjectSchema: z.ZodObject<{
22
+ kind: z.ZodLiteral<"agent">;
23
+ id: z.ZodString;
24
+ }, z.core.$strict>;
25
+ export type VaultSubject = z.output<typeof subjectSchema>;
26
+ declare const vaultHolderSchema: z.ZodObject<{
27
+ owner: z.ZodString;
28
+ subject: z.ZodObject<{
29
+ kind: z.ZodLiteral<"agent">;
30
+ id: z.ZodString;
31
+ }, z.core.$strict>;
32
+ }, z.core.$strict>;
33
+ /** Whose secrets one Agent command may name. */
34
+ export type VaultHolder = z.output<typeof vaultHolderSchema>;
35
+ /** The durable, secret-free context of one Agent command that may hold references. */
36
+ export declare function vaultExecutionContext(holder: VaultHolder): ComputerValue;
37
+ export declare function isVaultExecutionContext(context: ComputerValue): boolean;
38
+ /** One secret a subject holds, as its owner lists it: never the value. */
39
+ export type VaultSecretGrant = Readonly<{
40
+ name: string;
41
+ connectionId: string;
42
+ grantVersion: number;
43
+ }>;
44
+ /** The owner's live answer: which secrets this subject holds now. */
45
+ export type VaultGrantPort = Readonly<{
46
+ grants(holder: VaultHolder): Promise<readonly VaultSecretGrant[]>;
47
+ }>;
48
+ /** What a presented reference names, once the gateway resolves it. */
49
+ export type VaultReferenceAdmission = Readonly<{
50
+ invocationId: string;
51
+ owner: string;
52
+ subject: VaultSubject;
53
+ connectionId: string;
54
+ grantVersion: number;
55
+ }>;
56
+ /** This Computer's reference rows, in its own SQLite storage. */
57
+ export declare function createComputerVaultReferences(sql: WatchdogSqliteOwner["sql"]): {
58
+ /**
59
+ * One reference per granted secret, named by the secret. Names are taken
60
+ * in connection order; a repeated or non-portable name gets none.
61
+ */
62
+ issue(invocationId: string, { owner, subject }: VaultHolder, grants: readonly VaultSecretGrant[]): Promise<Readonly<Record<string, string>>>;
63
+ find(reference: string): Promise<VaultReferenceAdmission | null>;
64
+ close(invocationId: string): void;
65
+ };
66
+ export type ComputerVaultReferences = ReturnType<typeof createComputerVaultReferences>;
67
+ /**
68
+ * The host hooks for an Agent command's references. An owner that cannot
69
+ * answer gives the command no references; the command still runs, and it
70
+ * never holds a value either way.
71
+ */
72
+ export declare function vaultExecutionHooks(references: ComputerVaultReferences, port: VaultGrantPort): ComputerExecutionHostHooks;
73
+ /** A host's own credential hooks, with an Agent command's references beside them. */
74
+ export declare function withVaultExecution(vault: ComputerExecutionHostHooks, host: ComputerExecutionHostHooks): ComputerExecutionHostHooks;
75
+ export {};
@@ -0,0 +1,136 @@
1
+ import { z } from "zod";
2
+ import { reportCatchFailure } from "./failure.js";
3
+ const referencePrefix = "fvr1.";
4
+ /** 32 random bytes, base64url without padding. */
5
+ const referenceGrammar = /fvr1\.[A-Za-z0-9_-]{43}(?![A-Za-z0-9_-])/gu;
6
+ /** A POSIX-portable environment name; other secret names get no reference. */
7
+ const environmentName = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/u;
8
+ /** Every distinct reference written anywhere in `text`. */
9
+ export function vaultReferencesIn(text) {
10
+ return [...new Set(text.match(referenceGrammar) ?? [])];
11
+ }
12
+ const subjectSchema = z.strictObject({
13
+ kind: z.literal("agent"),
14
+ // Veil's Connection identifier grammar.
15
+ id: z.string().regex(/^[A-Za-z0-9_.:-]{1,128}$/u),
16
+ });
17
+ const vaultHolderSchema = z.strictObject({
18
+ /** The host's name for the secrets' owner: Hub's Team, Oyster's directory. */
19
+ owner: z.string().min(1).max(256),
20
+ subject: subjectSchema,
21
+ });
22
+ const vaultExecutionContextSchema = z.strictObject({
23
+ vault: vaultHolderSchema,
24
+ });
25
+ /** The durable, secret-free context of one Agent command that may hold references. */
26
+ export function vaultExecutionContext(holder) {
27
+ return vaultExecutionContextSchema.parse({ vault: holder });
28
+ }
29
+ export function isVaultExecutionContext(context) {
30
+ return vaultExecutionContextSchema.safeParse(context).success;
31
+ }
32
+ const referenceRowSchema = z.object({
33
+ invocation_id: z.string(),
34
+ owner: z.string(),
35
+ subject_kind: z.literal("agent"),
36
+ subject_id: z.string(),
37
+ connection_id: z.string(),
38
+ grant_version: z.number().int().positive(),
39
+ });
40
+ function mintReference() {
41
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
42
+ const base64 = btoa(String.fromCharCode(...bytes));
43
+ return `${referencePrefix}${base64.replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "")}`;
44
+ }
45
+ async function referenceDigest(reference) {
46
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(reference));
47
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
48
+ }
49
+ /** This Computer's reference rows, in its own SQLite storage. */
50
+ export function createComputerVaultReferences(sql) {
51
+ sql.exec(`CREATE TABLE IF NOT EXISTS computer_vault_references (
52
+ reference_digest TEXT PRIMARY KEY,
53
+ invocation_id TEXT NOT NULL,
54
+ owner TEXT NOT NULL,
55
+ subject_kind TEXT NOT NULL CHECK(subject_kind='agent'),
56
+ subject_id TEXT NOT NULL,
57
+ connection_id TEXT NOT NULL,
58
+ grant_version INTEGER NOT NULL
59
+ ) STRICT`);
60
+ sql.exec("CREATE INDEX IF NOT EXISTS computer_vault_references_invocation ON computer_vault_references(invocation_id)");
61
+ return {
62
+ /**
63
+ * One reference per granted secret, named by the secret. Names are taken
64
+ * in connection order; a repeated or non-portable name gets none.
65
+ */
66
+ async issue(invocationId, { owner, subject }, grants) {
67
+ const environment = {};
68
+ const ordered = [...grants].sort((left, right) => left.connectionId.localeCompare(right.connectionId));
69
+ for (const grant of ordered) {
70
+ if (!environmentName.test(grant.name) ||
71
+ Object.hasOwn(environment, grant.name))
72
+ continue;
73
+ const reference = mintReference();
74
+ sql.exec("INSERT INTO computer_vault_references VALUES(?,?,?,?,?,?,?)", await referenceDigest(reference), invocationId, owner, subject.kind, subject.id, grant.connectionId, grant.grantVersion);
75
+ environment[grant.name] = reference;
76
+ }
77
+ return environment;
78
+ },
79
+ async find(reference) {
80
+ if (vaultReferencesIn(reference)[0] !== reference)
81
+ return null;
82
+ const raw = sql
83
+ .exec("SELECT * FROM computer_vault_references WHERE reference_digest=?", await referenceDigest(reference))
84
+ .toArray()[0];
85
+ if (raw === undefined)
86
+ return null;
87
+ const row = referenceRowSchema.parse(raw);
88
+ return {
89
+ invocationId: row.invocation_id,
90
+ owner: row.owner,
91
+ subject: { kind: row.subject_kind, id: row.subject_id },
92
+ connectionId: row.connection_id,
93
+ grantVersion: row.grant_version,
94
+ };
95
+ },
96
+ close(invocationId) {
97
+ sql.exec("DELETE FROM computer_vault_references WHERE invocation_id=?", invocationId);
98
+ },
99
+ };
100
+ }
101
+ /**
102
+ * The host hooks for an Agent command's references. An owner that cannot
103
+ * answer gives the command no references; the command still runs, and it
104
+ * never holds a value either way.
105
+ */
106
+ export function vaultExecutionHooks(references, port) {
107
+ return {
108
+ async open(invocation, context) {
109
+ const holder = vaultExecutionContextSchema.parse(context).vault;
110
+ let grants;
111
+ try {
112
+ grants = await port.grants(holder);
113
+ }
114
+ catch (cause) {
115
+ // Still no references, but the failure is reported, never silent.
116
+ reportCatchFailure("computer.vault-grants", cause);
117
+ grants = [];
118
+ }
119
+ return { env: await references.issue(invocation.id, holder, grants) };
120
+ },
121
+ renew: () => Promise.resolve(),
122
+ close(invocation) {
123
+ references.close(invocation.id);
124
+ return Promise.resolve();
125
+ },
126
+ };
127
+ }
128
+ /** A host's own credential hooks, with an Agent command's references beside them. */
129
+ export function withVaultExecution(vault, host) {
130
+ const pick = (context) => isVaultExecutionContext(context) ? vault : host;
131
+ return {
132
+ open: (invocation, context) => pick(context).open(invocation, context),
133
+ renew: (invocation, context) => pick(context).renew(invocation, context),
134
+ close: (invocation, context, reason) => pick(context).close(invocation, context, reason),
135
+ };
136
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fungi.computer/computer",
3
- "version": "0.14.8",
3
+ "version": "0.15.0",
4
4
  "author": "Levi <levi@technomancy.dev>",
5
5
  "description": "Cloudflare Computer host for one durable Fungi Computer",
6
6
  "type": "module",