@query-farm/vgi 0.48.4 → 0.48.5
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/README.md +51 -0
- package/dist/attach-secret-keyfile.d.ts +11 -0
- package/dist/attach-secret-options.d.ts +96 -0
- package/dist/catalog/attach-option.d.ts +6 -0
- package/dist/catalog/interface.d.ts +15 -0
- package/dist/client-entry.js +1 -1
- package/dist/client-entry.js.map +4 -4
- package/dist/index.core.d.ts +2 -0
- package/dist/index.js +5700 -5276
- package/dist/index.js.map +24 -22
- package/dist/protocol/dispatch.d.ts +11 -0
- package/dist/protocol/handlers/catalog/admin.d.ts +1 -1
- package/dist/protocol/handlers/catalog/index.d.ts +1 -1
- package/dist/protocol/handlers/catalog/index_methods.d.ts +1 -1
- package/dist/protocol/handlers/catalog/macro.d.ts +1 -1
- package/dist/protocol/handlers/catalog/shared.d.ts +28 -3
- package/dist/protocol/handlers/catalog/table.d.ts +1 -1
- package/dist/protocol/handlers/catalog/view.d.ts +1 -1
- package/dist/protocol/handlers/function.d.ts +2 -0
- package/dist/protocol/handlers/table-buffering.d.ts +1 -1
- package/dist/serve-entry.d.ts +5 -0
- package/dist/serve-entry.js +475 -94
- package/dist/serve-entry.js.map +18 -16
- package/dist/worker-cf-entry.js +497 -93
- package/dist/worker-cf-entry.js.map +18 -16
- package/dist/worker.d.ts +10 -0
- package/package.json +1 -1
- package/src/attach-secret-keyfile.ts +185 -0
- package/src/attach-secret-options.ts +418 -0
- package/src/catalog/attach-option.ts +6 -0
- package/src/catalog/interface.ts +19 -0
- package/src/index.core.ts +10 -0
- package/src/protocol/dispatch.ts +14 -2
- package/src/protocol/handlers/catalog/admin.ts +33 -18
- package/src/protocol/handlers/catalog/index.ts +6 -5
- package/src/protocol/handlers/catalog/index_methods.ts +5 -3
- package/src/protocol/handlers/catalog/macro.ts +7 -5
- package/src/protocol/handlers/catalog/shared.ts +52 -6
- package/src/protocol/handlers/catalog/table.ts +24 -22
- package/src/protocol/handlers/catalog/view.ts +9 -7
- package/src/protocol/handlers/function.ts +11 -5
- package/src/protocol/handlers/table-buffering.ts +2 -1
- package/src/serve-entry.ts +6 -1
- package/src/worker.ts +12 -0
package/dist/worker.d.ts
CHANGED
|
@@ -19,12 +19,22 @@ export interface WorkerConfig extends HostingOptions {
|
|
|
19
19
|
* dispatches on. Omit to have the worker create its own.
|
|
20
20
|
*/
|
|
21
21
|
registry?: FunctionRegistry;
|
|
22
|
+
/**
|
|
23
|
+
* Optional root key for secret ATTACH options (`AttachOptionSpec.secret`),
|
|
24
|
+
* which the framework encrypts inside `attach_opaque_data` for
|
|
25
|
+
* `attachOptions()`. Defaults to the host-local key file
|
|
26
|
+
* (`$VGI_ATTACH_SECRET_KEY_FILE`, else `vgi/attach-secret-options.key` under
|
|
27
|
+
* `$XDG_RUNTIME_DIR` or the per-user temp dir). Every worker process that may
|
|
28
|
+
* receive a given attach must use the same key.
|
|
29
|
+
*/
|
|
30
|
+
attachSecretKey?: Uint8Array;
|
|
22
31
|
}
|
|
23
32
|
export declare class Worker {
|
|
24
33
|
private _registry;
|
|
25
34
|
private _hosting;
|
|
26
35
|
private _catalogInterface;
|
|
27
36
|
private _catalogName;
|
|
37
|
+
private _attachSecretKey;
|
|
28
38
|
constructor(config: WorkerConfig);
|
|
29
39
|
run(argv?: readonly string[]): void;
|
|
30
40
|
private _serve;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@query-farm/vgi",
|
|
3
|
-
"version": "0.48.
|
|
3
|
+
"version": "0.48.5",
|
|
4
4
|
"description": "TypeScript framework for extending DuckDB with user-defined functions via the Vector Gateway Interface (VGI) over Arrow IPC.",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"author": "Query Farm LLC (https://query.farm)",
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
// Copyright 2025, 2026 Query Farm LLC - https://query.farm
|
|
2
|
+
// SPDX-License-Identifier: LicenseRef-QueryFarm-Source-Available-1.0
|
|
3
|
+
|
|
4
|
+
// The host-local root key for secret ATTACH options on OS-owned transports
|
|
5
|
+
// (stdio, AF_UNIX, launcher pools), where there is no signing key. Shared by
|
|
6
|
+
// every VGI worker of this user on this host, whatever its SDK, so a launcher
|
|
7
|
+
// pool's processes — and workers of different SDKs — agree on it.
|
|
8
|
+
//
|
|
9
|
+
// Identical across SDKs (SPEC-secret-options.md, requirement 4):
|
|
10
|
+
// path $VGI_ATTACH_SECRET_KEY_FILE if set and non-empty; else
|
|
11
|
+
// $XDG_RUNTIME_DIR/vgi/attach-secret-options.key if XDG_RUNTIME_DIR is
|
|
12
|
+
// a directory; else <os.tmpdir()>/vgi-<username>/attach-secret-options.key
|
|
13
|
+
// content exactly 32 raw CSPRNG bytes
|
|
14
|
+
// perms directory 0700, file 0600, both owned by this user and not
|
|
15
|
+
// group/other-accessible (POSIX) — refused otherwise
|
|
16
|
+
// create temp file (0600) in the same directory, hard-linked into place;
|
|
17
|
+
// an existing key is never overwritten, concurrent first starts agree
|
|
18
|
+
//
|
|
19
|
+
// Node / Bun only (it needs a filesystem), and read only when a secret option
|
|
20
|
+
// actually has a value.
|
|
21
|
+
|
|
22
|
+
type NodeFs = typeof import("node:fs");
|
|
23
|
+
type NodeOs = typeof import("node:os");
|
|
24
|
+
type NodePath = typeof import("node:path");
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Node built-ins via `process.getBuiltinModule` (Node >= 22.3, Bun) rather than
|
|
28
|
+
* static imports, so the browser / workerd bundles that reach this module
|
|
29
|
+
* through the catalog code carry no `node:` imports. Throws where there is no
|
|
30
|
+
* filesystem; the caller turns that into "no key available".
|
|
31
|
+
*/
|
|
32
|
+
function builtins(): { fs: NodeFs; os: NodeOs; path: NodePath } {
|
|
33
|
+
const proc = (globalThis as { process?: { getBuiltinModule?: (id: string) => unknown } }).process;
|
|
34
|
+
const get = proc?.getBuiltinModule?.bind(proc);
|
|
35
|
+
const fs = get?.("node:fs") as NodeFs | undefined;
|
|
36
|
+
const os = get?.("node:os") as NodeOs | undefined;
|
|
37
|
+
const path = get?.("node:path") as NodePath | undefined;
|
|
38
|
+
if (!fs || !os || !path) throw new Error("this runtime has no filesystem for the host-local attach secret key file.");
|
|
39
|
+
return { fs, os, path };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export const ATTACH_SECRET_KEY_FILE_ENV = "VGI_ATTACH_SECRET_KEY_FILE";
|
|
43
|
+
const KEY_LEN = 32;
|
|
44
|
+
const FILE_NAME = "attach-secret-options.key";
|
|
45
|
+
const REMEDY = "Set VGI_SIGNING_KEY (or configure attachSecretKey), or point VGI_ATTACH_SECRET_KEY_FILE at a valid key file.";
|
|
46
|
+
|
|
47
|
+
function username(): string {
|
|
48
|
+
try {
|
|
49
|
+
const name = builtins().os.userInfo().username;
|
|
50
|
+
if (name) return name;
|
|
51
|
+
} catch {
|
|
52
|
+
// no passwd entry (containers): fall through
|
|
53
|
+
}
|
|
54
|
+
return process.env.USER || process.env.USERNAME || String(process.getuid?.() ?? "user");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function isDirectory(path: string): boolean {
|
|
58
|
+
try {
|
|
59
|
+
return builtins().fs.statSync(path).isDirectory();
|
|
60
|
+
} catch {
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The key file path this process uses, per the cross-SDK rules above. */
|
|
66
|
+
export function hostLocalAttachSecretKeyPath(env: Record<string, string | undefined> = (globalThis as { process?: { env: Record<string, string | undefined> } }).process?.env ?? {}): string {
|
|
67
|
+
const { os, path: { join } } = builtins();
|
|
68
|
+
const explicit = env[ATTACH_SECRET_KEY_FILE_ENV];
|
|
69
|
+
if (explicit) return explicit;
|
|
70
|
+
const xdg = env.XDG_RUNTIME_DIR;
|
|
71
|
+
if (xdg && isDirectory(xdg)) return join(xdg, "vgi", FILE_NAME);
|
|
72
|
+
return join(os.tmpdir(), `vgi-${username()}`, FILE_NAME);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const POSIX = typeof process === "undefined" || process.platform !== "win32";
|
|
76
|
+
|
|
77
|
+
function checkOwnedPrivate(path: string, mode: number, uid: number, what: string): void {
|
|
78
|
+
if (!POSIX) return;
|
|
79
|
+
const me = process.getuid?.();
|
|
80
|
+
if (me !== undefined && uid !== me) {
|
|
81
|
+
throw new Error(`attach secret key ${what} ${path} is not owned by the current user. ${REMEDY}`);
|
|
82
|
+
}
|
|
83
|
+
if ((mode & 0o077) !== 0) {
|
|
84
|
+
throw new Error(
|
|
85
|
+
`attach secret key ${what} ${path} is accessible by group/other (mode ${(mode & 0o777).toString(8)}); ` +
|
|
86
|
+
`it must be ${what === "directory" ? "0700" : "0600"}. ${REMEDY}`,
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function ensureDir(dir: string): void {
|
|
92
|
+
const { mkdirSync, lstatSync } = builtins().fs;
|
|
93
|
+
try {
|
|
94
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
95
|
+
} catch (e) {
|
|
96
|
+
if ((e as NodeJS.ErrnoException).code !== "EEXIST") throw e;
|
|
97
|
+
}
|
|
98
|
+
const st = lstatSync(dir);
|
|
99
|
+
if (!st.isDirectory()) throw new Error(`attach secret key directory ${dir} is not a directory. ${REMEDY}`);
|
|
100
|
+
checkOwnedPrivate(dir, st.mode, st.uid, "directory");
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function readKey(path: string): Uint8Array | null {
|
|
104
|
+
const { openSync, fstatSync, readSync, closeSync, constants } = builtins().fs;
|
|
105
|
+
let fd: number;
|
|
106
|
+
try {
|
|
107
|
+
fd = openSync(path, constants.O_RDONLY | (POSIX ? constants.O_NOFOLLOW : 0));
|
|
108
|
+
} catch (e) {
|
|
109
|
+
if ((e as NodeJS.ErrnoException).code === "ENOENT") return null;
|
|
110
|
+
throw new Error(`attach secret key file ${path} cannot be opened (${(e as NodeJS.ErrnoException).code}). ${REMEDY}`);
|
|
111
|
+
}
|
|
112
|
+
try {
|
|
113
|
+
const st = fstatSync(fd);
|
|
114
|
+
if (!st.isFile()) throw new Error(`attach secret key file ${path} is not a regular file. ${REMEDY}`);
|
|
115
|
+
checkOwnedPrivate(path, st.mode, st.uid, "file");
|
|
116
|
+
const buf = new Uint8Array(KEY_LEN + 1);
|
|
117
|
+
let n = 0;
|
|
118
|
+
for (;;) {
|
|
119
|
+
const got = readSync(fd, buf, n, buf.length - n, null);
|
|
120
|
+
if (got <= 0) break;
|
|
121
|
+
n += got;
|
|
122
|
+
if (n === buf.length) break;
|
|
123
|
+
}
|
|
124
|
+
if (n !== KEY_LEN || st.size !== KEY_LEN) {
|
|
125
|
+
throw new Error(
|
|
126
|
+
`attach secret key file ${path} must contain exactly ${KEY_LEN} raw bytes (found ${st.size}). ${REMEDY}`,
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
return buf.subarray(0, KEY_LEN);
|
|
130
|
+
} finally {
|
|
131
|
+
closeSync(fd);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Create the key atomically unless it exists; never overwrite one. */
|
|
136
|
+
function createKey(path: string): void {
|
|
137
|
+
const { openSync, writeSync, fsyncSync, closeSync, linkSync, unlinkSync, constants } = builtins().fs;
|
|
138
|
+
const { dirname, join } = builtins().path;
|
|
139
|
+
const tmp = join(dirname(path), `.${FILE_NAME}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
|
|
140
|
+
const fd = openSync(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);
|
|
141
|
+
try {
|
|
142
|
+
const key = crypto.getRandomValues(new Uint8Array(KEY_LEN));
|
|
143
|
+
let off = 0;
|
|
144
|
+
while (off < KEY_LEN) off += writeSync(fd, key, off, KEY_LEN - off);
|
|
145
|
+
fsyncSync(fd);
|
|
146
|
+
} finally {
|
|
147
|
+
closeSync(fd);
|
|
148
|
+
}
|
|
149
|
+
try {
|
|
150
|
+
linkSync(tmp, path);
|
|
151
|
+
} catch (e) {
|
|
152
|
+
// Another process won the race: use its key.
|
|
153
|
+
if ((e as NodeJS.ErrnoException).code !== "EEXIST") {
|
|
154
|
+
unlinkSync(tmp);
|
|
155
|
+
throw e;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
unlinkSync(tmp);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Read (creating on first use) the host-local key file at `path`
|
|
163
|
+
* (default {@link hostLocalAttachSecretKeyPath}). Synchronous and uncached;
|
|
164
|
+
* see {@link hostLocalAttachSecretKey} for the cached form the framework uses.
|
|
165
|
+
*/
|
|
166
|
+
export function loadHostLocalAttachSecretKey(path: string = hostLocalAttachSecretKeyPath()): Uint8Array {
|
|
167
|
+
ensureDir(builtins().path.dirname(path));
|
|
168
|
+
const existing = readKey(path);
|
|
169
|
+
if (existing) return existing;
|
|
170
|
+
createKey(path);
|
|
171
|
+
const created = readKey(path);
|
|
172
|
+
if (!created) throw new Error(`attach secret key file ${path} vanished after creation. ${REMEDY}`);
|
|
173
|
+
return created;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
let cached: { path: string; key: Uint8Array } | undefined;
|
|
177
|
+
|
|
178
|
+
/** The host-local root key, read once per process (per resolved path). */
|
|
179
|
+
export async function hostLocalAttachSecretKey(): Promise<Uint8Array> {
|
|
180
|
+
const path = hostLocalAttachSecretKeyPath();
|
|
181
|
+
if (cached?.path === path) return cached.key;
|
|
182
|
+
const key = loadHostLocalAttachSecretKey(path);
|
|
183
|
+
cached = { path, key };
|
|
184
|
+
return key;
|
|
185
|
+
}
|
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
// Copyright 2025, 2026 Query Farm LLC - https://query.farm
|
|
2
|
+
// SPDX-License-Identifier: LicenseRef-QueryFarm-Source-Available-1.0
|
|
3
|
+
|
|
4
|
+
// Framework-owned delivery of ATTACH options to functions and transaction
|
|
5
|
+
// hooks — secret ones (`AttachOptionSpec.secret`) encrypted with a key the
|
|
6
|
+
// client never has.
|
|
7
|
+
//
|
|
8
|
+
// The client hands `attach_opaque_data` back on every function call and hook,
|
|
9
|
+
// so the attach value is the only thing that can carry an option from
|
|
10
|
+
// `catalog_attach` to a later call: a catalog_attach and the function calls of
|
|
11
|
+
// its queries may run in different worker processes (launcher pools, HTTP). On
|
|
12
|
+
// HTTP the whole value is sealed, but on stdio / AF_UNIX it is raw bytes the
|
|
13
|
+
// client can read, and the sealing spec's rule 5 forbids a secret in plaintext
|
|
14
|
+
// in any opaque value. So the framework packs the options itself, after the
|
|
15
|
+
// catalog's own bytes, and encrypts the secret ones (SPEC-secret-options.md):
|
|
16
|
+
//
|
|
17
|
+
// framework attach plaintext = uuid(16) || catalog_bytes || trailer
|
|
18
|
+
// trailer = body || u32le(len(body)) || TRAILER_MAGIC(8)
|
|
19
|
+
// body = u32le(len(plain)) || plain || secret
|
|
20
|
+
// plain = Arrow IPC batch (1 row) of the non-secret options, or empty
|
|
21
|
+
// secret = empty, or SECRET_VERSION(1) || nonce(24) || XChaCha20-Poly1305(
|
|
22
|
+
// ciphertext || tag) of an Arrow IPC batch of the secret options
|
|
23
|
+
// AEAD key = HKDF-SHA256(root, salt = "", info = "vgi.attach_secret_options.v1", 32)
|
|
24
|
+
// AAD = "vgi.attach_secret_options.v1" 0x00 || uuid
|
|
25
|
+
//
|
|
26
|
+
// `root` is the explicitly configured `attachSecretKey`, else the HTTP signing
|
|
27
|
+
// key (when the worker seals), else the host-local key file shared by every
|
|
28
|
+
// VGI worker of this user on this host (./attach-secret-keyfile.ts). The AAD
|
|
29
|
+
// binds the blob to its attach's framework UUID, so a blob copied into another
|
|
30
|
+
// attach value does not open. XChaCha20-Poly1305 comes from @noble/ciphers
|
|
31
|
+
// (pure JS: Node, Bun, browsers, workerd); HKDF from WebCrypto.
|
|
32
|
+
//
|
|
33
|
+
// Catalog and function code never sees the trailer: the framework strips it
|
|
34
|
+
// (with the UUID) before any catalog or function body runs, and records the
|
|
35
|
+
// decoded options against the opened bytes, where `attachOptions()` finds
|
|
36
|
+
// them. An attach with no options carries no trailer at all, so its bytes are
|
|
37
|
+
// exactly what they were before this module existed.
|
|
38
|
+
|
|
39
|
+
import { xchacha20poly1305 } from "@noble/ciphers/chacha.js";
|
|
40
|
+
import {
|
|
41
|
+
batchFromColumns,
|
|
42
|
+
deserializeBatch,
|
|
43
|
+
iterRows,
|
|
44
|
+
schema as makeSchema,
|
|
45
|
+
serializeBatch,
|
|
46
|
+
type VgiField,
|
|
47
|
+
} from "./arrow/index.js";
|
|
48
|
+
import { OpaqueDataRejectedError } from "./crypto.js";
|
|
49
|
+
import { hostLocalAttachSecretKey } from "./attach-secret-keyfile.js";
|
|
50
|
+
|
|
51
|
+
const UTF8 = new TextEncoder();
|
|
52
|
+
|
|
53
|
+
/** HKDF `info`, and the AAD prefix (before the 0x00 and the attach uuid). */
|
|
54
|
+
export const ATTACH_SECRET_OPTIONS_INFO = "vgi.attach_secret_options.v1";
|
|
55
|
+
|
|
56
|
+
/** First byte of the secret blob: XChaCha20-Poly1305 with a 24-byte nonce. */
|
|
57
|
+
export const ATTACH_SECRET_OPTIONS_VERSION = 1;
|
|
58
|
+
|
|
59
|
+
/** Last 8 bytes of a framework attach plaintext that carries options. */
|
|
60
|
+
const TRAILER_MAGIC = Uint8Array.of(0x00, 0x56, 0x47, 0x49, 0x41, 0x4f, 0x01, 0xff); // \0 V G I A O \1 \xff
|
|
61
|
+
const TRAILER_FIXED = 4 + TRAILER_MAGIC.length;
|
|
62
|
+
const NONCE_LEN = 24;
|
|
63
|
+
const TAG_LEN = 16;
|
|
64
|
+
const AAD_PREFIX = UTF8.encode(`${ATTACH_SECRET_OPTIONS_INFO}\0`);
|
|
65
|
+
const UUID_LEN = 16;
|
|
66
|
+
const FIELD = "attach_opaque_data";
|
|
67
|
+
|
|
68
|
+
/** A decoded ATTACH options record: option name → value, as `attach()` got it. */
|
|
69
|
+
export type AttachOptionValues = Readonly<Record<string, unknown>>;
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Where the secret-options root key comes from. `explicit` is the optional
|
|
73
|
+
* `attachSecretKey` configuration; `signingKey` the HTTP sealing key.
|
|
74
|
+
* `hostLocal` is resolved lazily, and only when a secret option has a value.
|
|
75
|
+
*/
|
|
76
|
+
export interface AttachSecretKeySource {
|
|
77
|
+
explicit?: Uint8Array | undefined;
|
|
78
|
+
signingKey?: Uint8Array | undefined;
|
|
79
|
+
/** Override for tests; defaults to the host-local key file. */
|
|
80
|
+
hostLocal?: (() => Promise<Uint8Array>) | undefined;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Raised when a secret option has a value but no key can be obtained. */
|
|
84
|
+
export class AttachSecretKeyUnavailableError extends Error {
|
|
85
|
+
constructor(message: string) {
|
|
86
|
+
super(message);
|
|
87
|
+
this.name = "AttachSecretKeyUnavailableError";
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Raised by {@link attachOptions} for bytes the framework did not hand out. */
|
|
92
|
+
export class AttachOptionsUnavailableError extends Error {
|
|
93
|
+
constructor() {
|
|
94
|
+
super(
|
|
95
|
+
"attachOptions(): these bytes are not an attach_opaque_data value the framework handed to this call. " +
|
|
96
|
+
"Pass the attach value exactly as received (bindCall.attach_opaque_data, a TableBuffering attachId, or a " +
|
|
97
|
+
"catalog method's attachOpaqueData argument, or a subarray of it), not a copy.",
|
|
98
|
+
);
|
|
99
|
+
this.name = "AttachOptionsUnavailableError";
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ----------------------------------------------------------------- the key
|
|
104
|
+
|
|
105
|
+
const subkeys = new Map<string, Promise<Uint8Array>>();
|
|
106
|
+
|
|
107
|
+
function hexOf(b: Uint8Array): string {
|
|
108
|
+
let s = "";
|
|
109
|
+
for (let i = 0; i < b.length; i++) s += b[i]!.toString(16).padStart(2, "0");
|
|
110
|
+
return s;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* The AEAD key for secret ATTACH options derived from `root`:
|
|
115
|
+
* HKDF-SHA256(ikm = root, salt = empty, info = "vgi.attach_secret_options.v1", L = 32).
|
|
116
|
+
* The root itself is never used as the cipher key.
|
|
117
|
+
*/
|
|
118
|
+
export function deriveAttachSecretKey(root: Uint8Array): Promise<Uint8Array> {
|
|
119
|
+
const id = hexOf(root);
|
|
120
|
+
let derived = subkeys.get(id);
|
|
121
|
+
if (!derived) {
|
|
122
|
+
derived = (async () => {
|
|
123
|
+
const ikm = await crypto.subtle.importKey("raw", root as BufferSource, "HKDF", false, ["deriveBits"]);
|
|
124
|
+
const bits = await crypto.subtle.deriveBits(
|
|
125
|
+
{ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: UTF8.encode(ATTACH_SECRET_OPTIONS_INFO) },
|
|
126
|
+
ikm,
|
|
127
|
+
256,
|
|
128
|
+
);
|
|
129
|
+
return new Uint8Array(bits);
|
|
130
|
+
})();
|
|
131
|
+
subkeys.set(id, derived);
|
|
132
|
+
// A failed derivation must not stick.
|
|
133
|
+
derived.catch(() => subkeys.delete(id));
|
|
134
|
+
}
|
|
135
|
+
return derived;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function defaultHostLocal(): Promise<Uint8Array> {
|
|
139
|
+
return hostLocalAttachSecretKey();
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function noKeyMessage(): string {
|
|
143
|
+
return (
|
|
144
|
+
"A secret ATTACH option has a value but this worker has no key to encrypt it with: configure " +
|
|
145
|
+
"`attachSecretKey`, run with a signing key (VGI_SIGNING_KEY), or run where the host-local key file " +
|
|
146
|
+
"(VGI_ATTACH_SECRET_KEY_FILE) can be used."
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The root key: explicit, else the signing key, else the host-local key. */
|
|
151
|
+
async function rootKey(source: AttachSecretKeySource): Promise<Uint8Array> {
|
|
152
|
+
if (source.explicit && source.explicit.length > 0) return source.explicit;
|
|
153
|
+
if (source.signingKey && source.signingKey.length > 0) return source.signingKey;
|
|
154
|
+
return (source.hostLocal ?? defaultHostLocal)();
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function aadFor(uuid: Uint8Array): Uint8Array {
|
|
158
|
+
const out = new Uint8Array(AAD_PREFIX.length + uuid.length);
|
|
159
|
+
out.set(AAD_PREFIX, 0);
|
|
160
|
+
out.set(uuid, AAD_PREFIX.length);
|
|
161
|
+
return out;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// ------------------------------------------------------------------ packing
|
|
165
|
+
|
|
166
|
+
function u32le(n: number): Uint8Array {
|
|
167
|
+
const b = new Uint8Array(4);
|
|
168
|
+
new DataView(b.buffer).setUint32(0, n, true);
|
|
169
|
+
return b;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function readU32le(b: Uint8Array, off: number): number {
|
|
173
|
+
return new DataView(b.buffer, b.byteOffset, b.byteLength).getUint32(off, true);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function concat(...parts: Uint8Array[]): Uint8Array {
|
|
177
|
+
let total = 0;
|
|
178
|
+
for (const p of parts) total += p.length;
|
|
179
|
+
const out = new Uint8Array(total);
|
|
180
|
+
let off = 0;
|
|
181
|
+
for (const p of parts) {
|
|
182
|
+
out.set(p, off);
|
|
183
|
+
off += p.length;
|
|
184
|
+
}
|
|
185
|
+
return out;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Split a catalog_attach `options` IPC batch into one batch of the non-secret
|
|
190
|
+
* options and one of the secret options that have a value (a NULL secret is
|
|
191
|
+
* not a secret). `secretNames` are compared case-insensitively. Returns null
|
|
192
|
+
* for absent / empty options.
|
|
193
|
+
*/
|
|
194
|
+
function splitOptions(
|
|
195
|
+
optionsIpc: Uint8Array | null | undefined,
|
|
196
|
+
secretNames: ReadonlySet<string>,
|
|
197
|
+
): { plain: Uint8Array | null; secret: Uint8Array | null } | null {
|
|
198
|
+
if (!optionsIpc || optionsIpc.length === 0) return null;
|
|
199
|
+
const batch = deserializeBatch(optionsIpc);
|
|
200
|
+
if (batch.numRows === 0 || batch.schema.fields.length === 0) return null;
|
|
201
|
+
const row = (iterRows(batch).next().value ?? {}) as Record<string, unknown>;
|
|
202
|
+
const plainFields: VgiField[] = [];
|
|
203
|
+
const secretFields: VgiField[] = [];
|
|
204
|
+
const plainCols: Record<string, unknown[]> = {};
|
|
205
|
+
const secretCols: Record<string, unknown[]> = {};
|
|
206
|
+
for (const f of batch.schema.fields) {
|
|
207
|
+
const value = row[f.name];
|
|
208
|
+
if (secretNames.has(f.name.toLowerCase()) && value !== null && value !== undefined) {
|
|
209
|
+
secretFields.push(f);
|
|
210
|
+
secretCols[f.name] = [value];
|
|
211
|
+
} else {
|
|
212
|
+
plainFields.push(f);
|
|
213
|
+
plainCols[f.name] = [value ?? null];
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return {
|
|
217
|
+
plain: plainFields.length ? serializeBatch(batchFromColumns(plainCols, makeSchema(plainFields))) : null,
|
|
218
|
+
secret: secretFields.length ? serializeBatch(batchFromColumns(secretCols, makeSchema(secretFields))) : null,
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* The trailer the framework appends to `uuid || catalog_bytes` for an attach
|
|
224
|
+
* with options, or an empty array when there are none. Encrypts the secret
|
|
225
|
+
* options (obtaining the key only if there is one); never logs anything.
|
|
226
|
+
*
|
|
227
|
+
* @throws {AttachSecretKeyUnavailableError} A secret option has a value and no key can be obtained.
|
|
228
|
+
*/
|
|
229
|
+
export async function packAttachOptionsTrailer(
|
|
230
|
+
uuid: Uint8Array,
|
|
231
|
+
optionsIpc: Uint8Array | null | undefined,
|
|
232
|
+
secretNames: ReadonlySet<string>,
|
|
233
|
+
keys: AttachSecretKeySource,
|
|
234
|
+
fixedNonce?: Uint8Array,
|
|
235
|
+
): Promise<Uint8Array> {
|
|
236
|
+
const split = splitOptions(optionsIpc, secretNames);
|
|
237
|
+
if (split === null) return new Uint8Array(0);
|
|
238
|
+
const plain = split.plain ?? new Uint8Array(0);
|
|
239
|
+
let secret: Uint8Array = new Uint8Array(0);
|
|
240
|
+
if (split.secret) {
|
|
241
|
+
let root: Uint8Array;
|
|
242
|
+
try {
|
|
243
|
+
root = await rootKey(keys);
|
|
244
|
+
} catch (e) {
|
|
245
|
+
if (e instanceof AttachSecretKeyUnavailableError) throw e;
|
|
246
|
+
// The key file's own messages name the file and the remedies; keep them.
|
|
247
|
+
throw new AttachSecretKeyUnavailableError(`${noKeyMessage()} ${(e as Error).message}`);
|
|
248
|
+
}
|
|
249
|
+
const key = await deriveAttachSecretKey(root);
|
|
250
|
+
const nonce = fixedNonce ?? crypto.getRandomValues(new Uint8Array(NONCE_LEN));
|
|
251
|
+
const ct = xchacha20poly1305(key, nonce, aadFor(uuid)).encrypt(split.secret);
|
|
252
|
+
secret = concat(Uint8Array.of(ATTACH_SECRET_OPTIONS_VERSION), nonce, ct);
|
|
253
|
+
}
|
|
254
|
+
const body = concat(u32le(plain.length), plain, secret);
|
|
255
|
+
return concat(body, u32le(body.length), TRAILER_MAGIC);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function endsWithMagic(b: Uint8Array): boolean {
|
|
259
|
+
if (b.length < TRAILER_MAGIC.length) return false;
|
|
260
|
+
const off = b.length - TRAILER_MAGIC.length;
|
|
261
|
+
for (let i = 0; i < TRAILER_MAGIC.length; i++) if (b[off + i] !== TRAILER_MAGIC[i]) return false;
|
|
262
|
+
return true;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function decodeOptions(ipc: Uint8Array): Record<string, unknown> {
|
|
266
|
+
const batch = deserializeBatch(ipc);
|
|
267
|
+
if (batch.numRows === 0) return {};
|
|
268
|
+
return { ...((iterRows(batch).next().value ?? {}) as Record<string, unknown>) };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// --------------------------------------------------------------- accessor
|
|
272
|
+
|
|
273
|
+
/** Opened attach buffers → their options. Keyed by the ArrayBuffer so any view
|
|
274
|
+
* of the bytes the framework handed out (a composite's subarray) resolves. */
|
|
275
|
+
const registry = new WeakMap<ArrayBufferLike, AttachOptionValues>();
|
|
276
|
+
const EMPTY: AttachOptionValues = Object.freeze({});
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Turn a FULL framework attach plaintext (`uuid || catalog_bytes [|| trailer]`,
|
|
280
|
+
* already unsealed on HTTP) into the catalog's own bytes, decrypting any
|
|
281
|
+
* secret options and recording all options for {@link attachOptions}.
|
|
282
|
+
*
|
|
283
|
+
* Returns a view of a private copy, so the record cannot be confused with
|
|
284
|
+
* other bytes of the request. A value shorter than a UUID passes through
|
|
285
|
+
* as-is (with no options), as before.
|
|
286
|
+
*
|
|
287
|
+
* @throws {OpaqueDataRejectedError} The trailer is malformed or the secret blob
|
|
288
|
+
* does not open (wrong key, tampered, or moved from another attach).
|
|
289
|
+
*/
|
|
290
|
+
export async function openFrameworkAttach(full: Uint8Array, keys: AttachSecretKeySource): Promise<Uint8Array> {
|
|
291
|
+
if (full.length < UUID_LEN) return full;
|
|
292
|
+
const copy = full.slice();
|
|
293
|
+
let end = copy.length;
|
|
294
|
+
let options: AttachOptionValues = EMPTY;
|
|
295
|
+
if (copy.length >= UUID_LEN + TRAILER_FIXED && endsWithMagic(copy)) {
|
|
296
|
+
const bodyLen = readU32le(copy, copy.length - TRAILER_FIXED);
|
|
297
|
+
const bodyStart = copy.length - TRAILER_FIXED - bodyLen;
|
|
298
|
+
if (bodyLen < 4 || bodyStart < UUID_LEN) throw new OpaqueDataRejectedError(FIELD);
|
|
299
|
+
const body = copy.subarray(bodyStart, copy.length - TRAILER_FIXED);
|
|
300
|
+
const plainLen = readU32le(body, 0);
|
|
301
|
+
if (4 + plainLen > body.length) throw new OpaqueDataRejectedError(FIELD);
|
|
302
|
+
const plain = body.subarray(4, 4 + plainLen);
|
|
303
|
+
const secret = body.subarray(4 + plainLen);
|
|
304
|
+
const values: Record<string, unknown> = {};
|
|
305
|
+
try {
|
|
306
|
+
if (plain.length) Object.assign(values, decodeOptions(plain));
|
|
307
|
+
} catch {
|
|
308
|
+
throw new OpaqueDataRejectedError(FIELD);
|
|
309
|
+
}
|
|
310
|
+
if (secret.length) {
|
|
311
|
+
if (secret.length < 1 + NONCE_LEN + TAG_LEN || secret[0] !== ATTACH_SECRET_OPTIONS_VERSION) {
|
|
312
|
+
throw new OpaqueDataRejectedError(FIELD);
|
|
313
|
+
}
|
|
314
|
+
let opened: Uint8Array;
|
|
315
|
+
try {
|
|
316
|
+
const key = await deriveAttachSecretKey(await rootKey(keys));
|
|
317
|
+
const nonce = secret.subarray(1, 1 + NONCE_LEN);
|
|
318
|
+
opened = xchacha20poly1305(key, nonce, aadFor(copy.subarray(0, UUID_LEN))).decrypt(secret.subarray(1 + NONCE_LEN));
|
|
319
|
+
} catch {
|
|
320
|
+
// Uniform: no key, wrong key, tampered and moved all read the same.
|
|
321
|
+
throw new OpaqueDataRejectedError(FIELD);
|
|
322
|
+
}
|
|
323
|
+
try {
|
|
324
|
+
Object.assign(values, decodeOptions(opened));
|
|
325
|
+
} catch {
|
|
326
|
+
throw new OpaqueDataRejectedError(FIELD);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
options = Object.freeze(values);
|
|
330
|
+
end = bodyStart;
|
|
331
|
+
}
|
|
332
|
+
registry.set(copy.buffer, options);
|
|
333
|
+
return copy.subarray(UUID_LEN, end);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* The ATTACH options of the attach a call belongs to — every supplied option,
|
|
338
|
+
* secret ones included, decoded exactly as `CatalogInterface.attach()`
|
|
339
|
+
* received them.
|
|
340
|
+
*
|
|
341
|
+
* Pass the attach value the framework handed the call: `bindCall.attach_opaque_data`
|
|
342
|
+
* (bind, and `initCall.bind_call` at init/process, for every function kind), a
|
|
343
|
+
* table-buffering function's `attachId`, or the `attachOpaqueData` argument of
|
|
344
|
+
* a catalog method or transaction hook (`transactionBegin` / `transactionCommit`
|
|
345
|
+
* / `transactionRollback`). Any subarray of those bytes works too; a copy does
|
|
346
|
+
* not.
|
|
347
|
+
*
|
|
348
|
+
* Secret options (declared `secret: true`) reach this accessor on every
|
|
349
|
+
* transport without ever being in plaintext in `attach_opaque_data`: the
|
|
350
|
+
* framework encrypts them inside the attach value with a worker-held key. A
|
|
351
|
+
* catalog therefore never needs to pack options into its own attach bytes,
|
|
352
|
+
* and must not put a secret there.
|
|
353
|
+
*
|
|
354
|
+
* Returns `{}` for a null attach value (a call outside any attach) and for
|
|
355
|
+
* an attach that had no options.
|
|
356
|
+
*
|
|
357
|
+
* @throws {AttachOptionsUnavailableError} The bytes were not handed out by the framework.
|
|
358
|
+
*/
|
|
359
|
+
export function attachOptions(attachOpaqueData: Uint8Array | null | undefined): AttachOptionValues {
|
|
360
|
+
if (attachOpaqueData == null) return EMPTY;
|
|
361
|
+
// Looked up even when empty: a catalog whose own attach bytes are empty
|
|
362
|
+
// still gets a (zero-length) view of the framework value.
|
|
363
|
+
const found = registry.get(attachOpaqueData.buffer);
|
|
364
|
+
if (found !== undefined) return found;
|
|
365
|
+
if (attachOpaqueData.length === 0) return EMPTY;
|
|
366
|
+
throw new AttachOptionsUnavailableError();
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* One option from {@link attachOptions}, looked up case-insensitively (DuckDB
|
|
371
|
+
* option names are case-insensitive). `undefined` when it was not supplied.
|
|
372
|
+
*/
|
|
373
|
+
export function attachOption(attachOpaqueData: Uint8Array | null | undefined, name: string): unknown {
|
|
374
|
+
const all = attachOptions(attachOpaqueData);
|
|
375
|
+
if (Object.hasOwn(all, name)) return all[name];
|
|
376
|
+
const lower = name.toLowerCase();
|
|
377
|
+
for (const key of Object.keys(all)) if (key.toLowerCase() === lower) return all[key];
|
|
378
|
+
return undefined;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* Names (lower-cased) of the options `catalog` declares `secret: true` for
|
|
383
|
+
* catalog `name`, read from what it advertises in `catalogsInfo()` — the same
|
|
384
|
+
* specs the extension redacts by — or its `attachOptionSpecs(name)`.
|
|
385
|
+
*/
|
|
386
|
+
export async function secretAttachOptionNames(
|
|
387
|
+
catalog: {
|
|
388
|
+
catalogsInfo?(): unknown;
|
|
389
|
+
attachOptionSpecs?(name: string): Array<{ name: string; secret?: boolean }>;
|
|
390
|
+
},
|
|
391
|
+
name: string,
|
|
392
|
+
deserialize: (bytes: Uint8Array) => { name: string; secret?: boolean },
|
|
393
|
+
): Promise<Set<string>> {
|
|
394
|
+
const names = new Set<string>();
|
|
395
|
+
if (typeof catalog.attachOptionSpecs === "function") {
|
|
396
|
+
for (const spec of catalog.attachOptionSpecs(name) ?? []) if (spec.secret) names.add(spec.name.toLowerCase());
|
|
397
|
+
}
|
|
398
|
+
if (typeof catalog.catalogsInfo === "function") {
|
|
399
|
+
let infos: unknown;
|
|
400
|
+
try {
|
|
401
|
+
infos = await catalog.catalogsInfo();
|
|
402
|
+
} catch {
|
|
403
|
+
infos = [];
|
|
404
|
+
}
|
|
405
|
+
for (const info of (infos ?? []) as Array<{ name?: string; attach_option_specs?: unknown[] | null }>) {
|
|
406
|
+
if (info.name !== name) continue;
|
|
407
|
+
for (const raw of info.attach_option_specs ?? []) {
|
|
408
|
+
try {
|
|
409
|
+
const spec = deserialize(raw as Uint8Array);
|
|
410
|
+
if (spec.secret) names.add(spec.name.toLowerCase());
|
|
411
|
+
} catch {
|
|
412
|
+
// An undecodable spec declares nothing.
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
return names;
|
|
418
|
+
}
|
|
@@ -97,6 +97,12 @@ export interface AttachOptionSpec {
|
|
|
97
97
|
* api_key getenv('SALES_API_KEY'));
|
|
98
98
|
* ```
|
|
99
99
|
*
|
|
100
|
+
* Functions and transaction hooks read the value with `attachOptions()`
|
|
101
|
+
* (`CatalogInterface.attachOptions()` in hooks), like any other option: the
|
|
102
|
+
* framework carries it to them encrypted inside `attach_opaque_data` with a
|
|
103
|
+
* worker-held key, so it is never in plaintext in any opaque value. Never
|
|
104
|
+
* put a secret into your catalog's own attach bytes.
|
|
105
|
+
*
|
|
100
106
|
* Combines with `required` (a credential the catalog cannot attach without,
|
|
101
107
|
* which a client can then ask for before attaching). It is allowed together
|
|
102
108
|
* with `default`, but a secret option normally has none: a default would be
|
package/src/catalog/interface.ts
CHANGED
|
@@ -5,6 +5,7 @@ import type { CatalogSnapshotPolicy } from "./publication.js";
|
|
|
5
5
|
|
|
6
6
|
import { CatalogNotFoundError, CatalogReadOnlyError, VgiError } from "../errors.js";
|
|
7
7
|
import { schemaPathsEqual } from "../schema-path.js";
|
|
8
|
+
import { attachOptions } from "../attach-secret-options.js";
|
|
8
9
|
import type { CatalogCapabilities, ConstraintSnapshot, ConstraintsApplyRequest } from "../generated/vgi-protocol-types.js";
|
|
9
10
|
import { decodeCatalogObjectRef, decodeConstraintChange, decodeConstraintDefinition } from "../generated/vgi-protocol-types.js";
|
|
10
11
|
import { constraintCapabilities, readConstraintRecord } from "./constraints.js";
|
|
@@ -1248,6 +1249,24 @@ export abstract class CatalogInterface {
|
|
|
1248
1249
|
catalogContentsOwner(_attachOpaqueData: AttachOpaqueData): CatalogInterface {
|
|
1249
1250
|
return this;
|
|
1250
1251
|
}
|
|
1252
|
+
/**
|
|
1253
|
+
* The ATTACH options of the attach `attachOpaqueData` belongs to — every
|
|
1254
|
+
* supplied option, secret ones (`AttachOptionSpec.secret`) included, as
|
|
1255
|
+
* `attach()` received them. Works in every catalog method and transaction
|
|
1256
|
+
* hook (`transactionBegin` / `transactionCommit` / `transactionRollback`)
|
|
1257
|
+
* on the `attachOpaqueData` argument it was given; functions use the
|
|
1258
|
+
* standalone {@link attachOptions} on `bindCall.attach_opaque_data`.
|
|
1259
|
+
*
|
|
1260
|
+
* The framework carries the options inside `attach_opaque_data` itself and
|
|
1261
|
+
* encrypts the secret ones with a worker-held key, so they never appear in
|
|
1262
|
+
* plaintext in any opaque value on any transport. An `attach()` override
|
|
1263
|
+
* therefore never needs to pack options into its own attach bytes, and must
|
|
1264
|
+
* not put a credential there.
|
|
1265
|
+
*/
|
|
1266
|
+
attachOptions(attachOpaqueData: AttachOpaqueData): Readonly<Record<string, unknown>> {
|
|
1267
|
+
return attachOptions(attachOpaqueData);
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1251
1270
|
transactionBegin(attachOpaqueData: AttachOpaqueData): Awaitable<Uint8Array | null> {
|
|
1252
1271
|
return null;
|
|
1253
1272
|
}
|