History

Fix 1Password SDK wasm loading in compiled binaries and close the CI gap that hid it (#1298)

* Fix 1Password SDK loading in compiled sidecar * Fix compiled 1Password wasm loading * CI: run the compiled sidecar outside the build workspace

Rhys Sullivan committed 4 months ago

Commit 9ee4bcf1 parent 87ed7c910 files · +255 −16Browse files

Unified · Split

10 files
  1. .github/workflows/ci.yml +34 −0
  2. apps/cli/src/build.ts +17 −0
  3. apps/cli/src/main.ts +13 −6
  4. apps/desktop/scripts/smoke-sidecar.ts +103 −3
  5. bun.lock +1 −0
  6. package.json +1 −0
  7. packages/plugins/onepassword/src/sdk/onepassword-sdk.ts +8 −0
  8. packages/plugins/onepassword/src/sdk/service.test.ts +33 −4
  9. packages/plugins/onepassword/src/sdk/service.ts +21 −3
  10. patches/@1password%2Fsdk-core@0.4.1-beta.1.patch +24 −0
.github/workflows/ci.yml+34−0
@@ -342,6 +342,40 @@ jobs: · 341 unmodified lines
342 run: bun ./scripts/build-sidecar.ts342 run: bun ./scripts/build-sidecar.ts
343 working-directory: apps/desktop343 working-directory: apps/desktop
344 344
345 # Run the compiled sidecar in a clean container where the build
346 # workspace does not exist. bun --compile bakes build-machine paths
347 # into __dirname for runtime-loaded assets; running the binary on the
348 # build machine hides that entire failure class (this exact gap
349 # shipped a broken 1Password SDK: its sdk-core wasm was read from the
350 # CI runner's node_modules path at runtime, ENOENT on every user
351 # machine). Pass condition: the 1Password endpoint reaches real
352 # credential validation, not a module-load or empty-namespace error.
353 - name: Run sidecar outside the workspace
354 working-directory: apps/desktop
355 run: |
356 docker run --rm -d --name sidecar-smoke -p 45841:45841 -e HOME=/tmp \
357 -v "$PWD/resources/executor:/opt/executor:ro" \
358 debian:bookworm-slim /opt/executor/executor daemon run --foreground \
359 --port 45841 --hostname 0.0.0.0 --auth-token=ci-smoke
360 for i in $(seq 1 60); do
361 code=$(curl -s -o /dev/null -w '%{http_code}' -H "Authorization: Bearer ci-smoke" http://127.0.0.1:45841/api/onepassword/vaults || true)
362 [ "$code" != "000" ] && break
363 docker ps -q -f name=sidecar-smoke | grep -q . || { docker logs sidecar-smoke; exit 1; }
364 sleep 1
365 done
366 body=$(curl -s -H "Authorization: Bearer ci-smoke" \
367 "http://127.0.0.1:45841/api/onepassword/vaults?authKind=service-account&account=ops_ci_fake_token")
368 docker stop sidecar-smoke
369 echo "$body"
370 if echo "$body" | grep -qE "sdk module load|ENOENT|is not a function|not a constructor"; then
371 echo "::error::1Password SDK failed to load inside the compiled binary (baked build path or missing sibling asset)"
372 exit 1
373 fi
374 if ! echo "$body" | grep -q "invalid service account token"; then
375 echo "::error::sidecar did not reach 1Password credential validation; unexpected response above"
376 exit 1
377 fi
378
345 - name: Build Electron main/preload/renderer379 - name: Build Electron main/preload/renderer
346 run: bunx --bun electron-vite build380 run: bunx --bun electron-vite build
347 working-directory: apps/desktop381 working-directory: apps/desktop
apps/cli/src/build.ts+17−0
@@ -10,6 +10,7 @@ const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../.."); · 9 unmodified lines
10const cliRoot = resolve(repoRoot, "apps/cli");10const cliRoot = resolve(repoRoot, "apps/cli");
11const webRoot = resolve(repoRoot, "apps/local");11const webRoot = resolve(repoRoot, "apps/local");
12const distDir = resolve(cliRoot, "dist");12const distDir = resolve(cliRoot, "dist");
13const ONEPASSWORD_CORE_WASM_FILENAME = "onepassword-core_bg.wasm";
13 14
14const resolveQuickJsWasmPath = (): string => {15const resolveQuickJsWasmPath = (): string => {
15 const req = createRequire(join(repoRoot, "packages/kernel/runtime-quickjs/package.json"));16 const req = createRequire(join(repoRoot, "packages/kernel/runtime-quickjs/package.json"));
@@ -22,6 +23,16 @@ const resolveQuickJsWasmPath = (): string => { · 6 unmodified lines
22 return wasmPath;23 return wasmPath;
23};24};
24 25
26const resolveOnePasswordCoreWasmPath = (): string => {
27 const req = createRequire(join(repoRoot, "packages/plugins/onepassword/package.json"));
28 const sdkPkg = req.resolve("@1password/sdk/package.json");
29 const sdkReq = createRequire(sdkPkg);
30 const sdkCorePkg = sdkReq.resolve("@1password/sdk-core/package.json");
31 const wasmPath = join(dirname(sdkCorePkg), "nodejs/core_bg.wasm");
32 if (!existsSync(wasmPath)) throw new Error(`1Password SDK core WASM not found at ${wasmPath}`);
33 return wasmPath;
34};
35
25// ---------------------------------------------------------------------------36// ---------------------------------------------------------------------------
26// Metadata37// Metadata
27// ---------------------------------------------------------------------------38// ---------------------------------------------------------------------------
@@ -321,6 +332,7 @@ const buildBinaries = async (targets: Target[], mode: BuildMode) => { · 293 unmodified lines
321 await writeFile(embeddedMigrationsPath, `${embeddedMigrations}\n`);332 await writeFile(embeddedMigrationsPath, `${embeddedMigrations}\n`);
322 333
323 const quickJsWasmPath = resolveQuickJsWasmPath();334 const quickJsWasmPath = resolveQuickJsWasmPath();
335 const onePasswordCoreWasmPath = resolveOnePasswordCoreWasmPath();
324 336
325 try {337 try {
326 for (const target of targets) {338 for (const target of targets) {
@@ -343,6 +355,11 @@ const buildBinaries = async (targets: Target[], mode: BuildMode) => { · 16 unmodified lines
343 // Copy QuickJS WASM next to binary — loaded at runtime by the server355 // Copy QuickJS WASM next to binary — loaded at runtime by the server
344 await cp(quickJsWasmPath, join(binDir, "emscripten-module.wasm"));356 await cp(quickJsWasmPath, join(binDir, "emscripten-module.wasm"));
345 357
358 // Copy 1Password's sdk-core WASM next to the binary. The patched
359 // sdk-core loader falls back to this sibling file when bun --compile
360 // bakes a build-machine node_modules path into __dirname.
361 await cp(onePasswordCoreWasmPath, join(binDir, ONEPASSWORD_CORE_WASM_FILENAME));
362
346 // Copy @napi-rs/keyring native binding next to executor — bun --compile363 // Copy @napi-rs/keyring native binding next to executor — bun --compile
347 // doesn't bundle .node files, so the loader needs to find it on disk364 // doesn't bundle .node files, so the loader needs to find it on disk
348 // via NAPI_RS_NATIVE_LIBRARY_PATH (set in main.ts).365 // via NAPI_RS_NATIVE_LIBRARY_PATH (set in main.ts).
apps/cli/src/main.ts+13−6
@@ -4,13 +4,20 @@ import "./native-bindings"; · 3 unmodified lines
4 4
5import { randomUUID } from "node:crypto";5import { randomUUID } from "node:crypto";
6import { existsSync, realpathSync } from "node:fs";6import { existsSync, realpathSync } from "node:fs";
7import { dirname, join, resolve } from "node:path";7import { delimiter, dirname, join, resolve } from "node:path";
8// Make sibling binaries (if any are added later) discoverable on $PATH so8// Make sibling binaries and standard GUI-missing CLI install locations
9// child processes spawned without an absolute path still find them.9// discoverable on $PATH so child processes spawned without an absolute path
10// still find them.
10const execDir = dirname(process.execPath);11const execDir = dirname(process.execPath);
11if (process.env.PATH && !process.env.PATH.includes(execDir)) {12const prependPathEntries = (entries: ReadonlyArray<string>): void => {
12 process.env.PATH = `${execDir}:${process.env.PATH}`;13 const current = process.env.PATH?.split(delimiter).filter(Boolean) ?? [];
13}14 const next = [...entries.filter((entry) => !current.includes(entry)), ...current];
15 process.env.PATH = next.join(delimiter);
16};
17prependPathEntries([
18 execDir,
19 ...(process.platform === "darwin" ? ["/opt/homebrew/bin", "/usr/local/bin"] : []),
20]);
14 21
15// Pre-load QuickJS WASM for compiled binaries — must run before server imports22// Pre-load QuickJS WASM for compiled binaries — must run before server imports
16const wasmOnDisk = join(execDir, "emscripten-module.wasm");23const wasmOnDisk = join(execDir, "emscripten-module.wasm");
apps/desktop/scripts/smoke-sidecar.ts+103−3
@@ -16,16 +16,18 @@ · 15 unmodified lines
16 * Run after `bun ./scripts/build-sidecar.ts`. Exits non-zero on any16 * Run after `bun ./scripts/build-sidecar.ts`. Exits non-zero on any
17 * deviation so it can gate CI.17 * deviation so it can gate CI.
18 */18 */
19import { mkdtemp, rm } from "node:fs/promises";19import { chmod, cp, mkdtemp, rename, rm } from "node:fs/promises";
20import { createHash } from "node:crypto";20import { createHash } from "node:crypto";
21import { createRequire } from "node:module";
21import { tmpdir } from "node:os";22import { tmpdir } from "node:os";
22import { basename, join, resolve } from "node:path";23import { basename, dirname, join, resolve } from "node:path";
23import { spawn, type Subprocess } from "bun";24import { spawn, type Subprocess } from "bun";
24import { Database } from "bun:sqlite";25import { Database } from "bun:sqlite";
25import { Client } from "@modelcontextprotocol/sdk/client/index.js";26import { Client } from "@modelcontextprotocol/sdk/client/index.js";
26import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";27import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
27 28
28const ROOT = resolve(import.meta.dir, "..");29const ROOT = resolve(import.meta.dir, "..");
30const REPO_ROOT = resolve(ROOT, "../..");
29const APPS_LOCAL_DRIZZLE = resolve(ROOT, "../local/drizzle-legacy-v1");31const APPS_LOCAL_DRIZZLE = resolve(ROOT, "../local/drizzle-legacy-v1");
30const BINARY = resolve(32const BINARY = resolve(
31 ROOT,33 ROOT,
@@ -36,6 +38,17 @@ const BINARY = resolve( · 4 unmodified lines
36const AUTH_TOKEN = "smoke-test-token";38const AUTH_TOKEN = "smoke-test-token";
37const AUTH_HEADER = `Bearer ${AUTH_TOKEN}`;39const AUTH_HEADER = `Bearer ${AUTH_TOKEN}`;
38const READY_TIMEOUT_MS = 30_000;40const READY_TIMEOUT_MS = 30_000;
41const EXECUTOR_BINARY_NAME = process.platform === "win32" ? "executor.exe" : "executor";
42const requireFromOnePasswordPlugin = createRequire(
43 join(REPO_ROOT, "packages/plugins/onepassword/package.json"),
44);
45const requireFromOnePasswordSdk = createRequire(
46 requireFromOnePasswordPlugin.resolve("@1password/sdk/package.json"),
47);
48const ONEPASSWORD_SDK_CORE_WASM = join(
49 dirname(requireFromOnePasswordSdk.resolve("@1password/sdk-core/package.json")),
50 "nodejs/core_bg.wasm",
51);
39 52
40// Throw instead of process.exit so main()'s finally still tears down the53// Throw instead of process.exit so main()'s finally still tears down the
41// spawned daemon + temp dirs — exiting here leaks a running process.54// spawned daemon + temp dirs — exiting here leaks a running process.
@@ -319,6 +332,84 @@ const completePausedResult = async ( · 277 unmodified lines
319 return fail("execute still paused after 5 resume attempts");332 return fail("execute still paused after 5 resume attempts");
320};333};
321 334
335const stageSidecarWithUnavailableOp = async (
336 sidecarRoot: string,
337): Promise<{ readonly binary: string }> => {
338 const stagedDir = join(sidecarRoot, "executor");
339 await cp(dirname(BINARY), stagedDir, { recursive: true });
340
341 const fakeOpPath = join(stagedDir, process.platform === "win32" ? "op.cmd" : "op");
342 const fakeOp =
343 process.platform === "win32"
344 ? "@echo off\r\necho [ERROR] 2026/01/01 00:00:00 op: command not found 1>&2\r\nexit /b 127\r\n"
345 : "#!/bin/sh\necho '[ERROR] 2026/01/01 00:00:00 op: command not found' >&2\nexit 127\n";
346 await Bun.write(fakeOpPath, fakeOp);
347 if (process.platform !== "win32") {
348 await chmod(fakeOpPath, 0o755);
349 }
350
351 return { binary: join(stagedDir, EXECUTOR_BINARY_NAME) };
352};
353
354interface HiddenWorkspaceWasm {
355 readonly original: string;
356 readonly hidden: string;
357}
358
359const hideWorkspaceOnePasswordWasm = async (): Promise<HiddenWorkspaceWasm> => {
360 const hidden = `${ONEPASSWORD_SDK_CORE_WASM}.hidden`;
361 if (!(await Bun.file(ONEPASSWORD_SDK_CORE_WASM).exists())) {
362 fail(`workspace 1Password SDK WASM not found at ${ONEPASSWORD_SDK_CORE_WASM}`);
363 }
364
365 await rm(hidden, { force: true });
366 await rename(ONEPASSWORD_SDK_CORE_WASM, hidden);
367 console.log(`[smoke-sidecar] hid workspace 1Password SDK WASM: ${ONEPASSWORD_SDK_CORE_WASM}`);
368 return { original: ONEPASSWORD_SDK_CORE_WASM, hidden };
369};
370
371const restoreWorkspaceOnePasswordWasm = async (
372 hiddenWorkspaceWasm: HiddenWorkspaceWasm | null,
373): Promise<void> => {
374 if (!hiddenWorkspaceWasm) return;
375
376 if (await Bun.file(hiddenWorkspaceWasm.original).exists()) {
377 await rm(hiddenWorkspaceWasm.hidden, { force: true });
378 return;
379 }
380
381 if (!(await Bun.file(hiddenWorkspaceWasm.hidden).exists())) {
382 fail(`workspace 1Password SDK WASM restore source missing at ${hiddenWorkspaceWasm.hidden}`);
383 }
384
385 await rename(hiddenWorkspaceWasm.hidden, hiddenWorkspaceWasm.original);
386 console.log(`[smoke-sidecar] restored workspace 1Password SDK WASM`);
387};
388
389const assertOnePasswordSdkLoads = async (origin: string): Promise<void> => {
390 const url = new URL("/api/onepassword/vaults", origin);
391 url.searchParams.set("authKind", "service-account");
392 url.searchParams.set("account", "ops_fake_smoke_token");
393 const response = await fetch(url, { headers: { Authorization: AUTH_HEADER } });
394 const body = await response.text();
395
396 if (response.status !== 502) {
397 fail(`expected 1Password invalid-token 502, got ${response.status}: ${body}`);
398 }
399 if (
400 body.includes("createClient is not a function") ||
401 body.includes("undefined is not a constructor") ||
402 body.includes("did not expose createClient and DesktopAuth")
403 ) {
404 fail(`1Password SDK namespace did not load in compiled binary: ${body}`);
405 }
406 if (!body.includes("invalid service account token")) {
407 fail(`1Password SDK did not reach token validation: ${body}`);
408 }
409
410 console.log("[smoke-sidecar] OK - 1Password SDK reached service-account token validation");
411};
412
322const main = async () => {413const main = async () => {
323 if (!(await Bun.file(BINARY).exists())) {414 if (!(await Bun.file(BINARY).exists())) {
324 fail(415 fail(
@@ -328,6 +419,9 @@ const main = async () => { · 3 unmodified lines
328 419
329 const scopeDir = await mkdtemp(join(tmpdir(), "executor-smoke-scope-"));420 const scopeDir = await mkdtemp(join(tmpdir(), "executor-smoke-scope-"));
330 const dataDir = await mkdtemp(join(tmpdir(), "executor-smoke-data-"));421 const dataDir = await mkdtemp(join(tmpdir(), "executor-smoke-data-"));
422 const sidecarRoot = await mkdtemp(join(tmpdir(), "executor-smoke-sidecar-"));
423 const sidecar = await stageSidecarWithUnavailableOp(sidecarRoot);
424 let hiddenWorkspaceWasm: HiddenWorkspaceWasm | null = null;
331 await seedLegacyScopedSqlite(dataDir, makeScopeId(scopeDir));425 await seedLegacyScopedSqlite(dataDir, makeScopeId(scopeDir));
332 // v2 connections reference credentials by provider item instead of carrying426 // v2 connections reference credentials by provider item instead of carrying
333 // raw values, so seed the file-secrets provider (auth.json under427 // raw values, so seed the file-secrets provider (auth.json under
@@ -342,10 +436,11 @@ const main = async () => { · 8 unmodified lines
342 console.log(`[smoke-sidecar] scope: ${scopeDir}`);436 console.log(`[smoke-sidecar] scope: ${scopeDir}`);
343 console.log(`[smoke-sidecar] data: ${dataDir}`);437 console.log(`[smoke-sidecar] data: ${dataDir}`);
344 console.log(`[smoke-sidecar] openapi: ${openapi.origin}`);438 console.log(`[smoke-sidecar] openapi: ${openapi.origin}`);
439 console.log(`[smoke-sidecar] sidecar: ${sidecar.binary}`);
345 440
346 const proc = spawn({441 const proc = spawn({
347 cmd: [442 cmd: [
348 BINARY,443 sidecar.binary,
349 "daemon",444 "daemon",
350 "run",445 "run",
351 "--foreground",446 "--foreground",
@@ -380,12 +475,15 @@ const main = async () => { · 28 unmodified lines
380 if (exitCode === null) proc.kill("SIGKILL");475 if (exitCode === null) proc.kill("SIGKILL");
381 }476 }
382 openapi.server.stop(true);477 openapi.server.stop(true);
478 await restoreWorkspaceOnePasswordWasm(hiddenWorkspaceWasm);
383 // oxlint-disable-next-line executor/no-promise-catch -- boundary: best-effort tempdir cleanup in a standalone smoke harness479 // oxlint-disable-next-line executor/no-promise-catch -- boundary: best-effort tempdir cleanup in a standalone smoke harness
384 await rm(scopeDir, { recursive: true, force: true }).catch(() => {});480 await rm(scopeDir, { recursive: true, force: true }).catch(() => {});
385 // oxlint-disable-next-line executor/no-promise-catch -- boundary: best-effort tempdir cleanup in a standalone smoke harness481 // oxlint-disable-next-line executor/no-promise-catch -- boundary: best-effort tempdir cleanup in a standalone smoke harness
386 await rm(dataDir, { recursive: true, force: true }).catch(() => {});482 await rm(dataDir, { recursive: true, force: true }).catch(() => {});
387 // oxlint-disable-next-line executor/no-promise-catch -- boundary: best-effort tempdir cleanup in a standalone smoke harness483 // oxlint-disable-next-line executor/no-promise-catch -- boundary: best-effort tempdir cleanup in a standalone smoke harness
388 await rm(xdgDir, { recursive: true, force: true }).catch(() => {});484 await rm(xdgDir, { recursive: true, force: true }).catch(() => {});
485 // oxlint-disable-next-line executor/no-promise-catch -- boundary: best-effort tempdir cleanup in a standalone smoke harness
486 await rm(sidecarRoot, { recursive: true, force: true }).catch(() => {});
389 };487 };
390 488
391 // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: standalone smoke harness needs a finally to tear down the spawned binary + http server489 // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: standalone smoke harness needs a finally to tear down the spawned binary + http server
@@ -394,6 +492,8 @@ const main = async () => { · 2 unmodified lines
394 await assertV1MigrationCompleted(dataDir);492 await assertV1MigrationCompleted(dataDir);
395 const mcpUrl = new URL(`http://127.0.0.1:${port}/mcp`);493 const mcpUrl = new URL(`http://127.0.0.1:${port}/mcp`);
396 console.log(`[smoke-sidecar] ready on ${mcpUrl.origin}`);494 console.log(`[smoke-sidecar] ready on ${mcpUrl.origin}`);
495 hiddenWorkspaceWasm = await hideWorkspaceOnePasswordWasm();
496 await assertOnePasswordSdkLoads(mcpUrl.origin);
397 497
398 const transport = new StreamableHTTPClientTransport(mcpUrl, {498 const transport = new StreamableHTTPClientTransport(mcpUrl, {
399 requestInit: { headers: { Authorization: AUTH_HEADER } },499 requestInit: { headers: { Authorization: AUTH_HEADER } },
bun.lock+1−0
@@ -1215,6 +1215,7 @@ · 1214 unmodified lines
1215 },1215 },
1216 },1216 },
1217 "patchedDependencies": {1217 "patchedDependencies": {
1218 "@1password/sdk-core@0.4.1-beta.1": "patches/@1password%2Fsdk-core@0.4.1-beta.1.patch",
1218 "@electric-sql/pglite-socket@0.1.4": "patches/@electric-sql%2Fpglite-socket@0.1.4.patch",1219 "@electric-sql/pglite-socket@0.1.4": "patches/@electric-sql%2Fpglite-socket@0.1.4.patch",
1219 "libsql@0.5.29": "patches/libsql@0.5.29.patch",1220 "libsql@0.5.29": "patches/libsql@0.5.29.patch",
1220 "agents@0.17.3": "patches/agents@0.17.3.patch",1221 "agents@0.17.3": "patches/agents@0.17.3.patch",
package.json+1−0
@@ -129,6 +129,7 @@ · 128 unmodified lines
129 "@effect/opentelemetry": "4.0.0-beta.59"129 "@effect/opentelemetry": "4.0.0-beta.59"
130 },130 },
131 "patchedDependencies": {131 "patchedDependencies": {
132 "@1password/sdk-core@0.4.1-beta.1": "patches/@1password%2Fsdk-core@0.4.1-beta.1.patch",
132 "postgres@3.4.9": "patches/postgres@3.4.9.patch",133 "postgres@3.4.9": "patches/postgres@3.4.9.patch",
133 "@cloudflare/vite-plugin@1.31.2": "patches/@cloudflare%2Fvite-plugin@1.31.2.patch",134 "@cloudflare/vite-plugin@1.31.2": "patches/@cloudflare%2Fvite-plugin@1.31.2.patch",
134 "agents@0.17.3": "patches/agents@0.17.3.patch",135 "agents@0.17.3": "patches/agents@0.17.3.patch",
packages/plugins/onepassword/src/sdk/onepassword-sdk.ts+8−0
@@ -0,0 +1,8 @@
1import * as sdk from "@1password/sdk";
2
3export type OnePasswordSdkModule = typeof sdk;
4
5// Keep the package import static in this local shim. The service dynamically
6// imports this file so normal app boot stays lazy, while Bun's compiler sees
7// the concrete @1password/sdk dependency and its sdk-core WASM loader.
8export const onePasswordSdk: OnePasswordSdkModule = sdk;
packages/plugins/onepassword/src/sdk/service.test.ts+33−4
@@ -17,6 +17,10 @@ const opMocks = vi.hoisted(() => ({ · 16 unmodified lines
17const sdkMocks = vi.hoisted(() => ({17const sdkMocks = vi.hoisted(() => ({
18 createClient: vi.fn(),18 createClient: vi.fn(),
19 DesktopAuth: vi.fn((accountName: string) => ({ accountName })),19 DesktopAuth: vi.fn((accountName: string) => ({ accountName })),
20 exports: {} as {
21 createClient?: unknown;
22 DesktopAuth?: unknown;
23 },
20}));24}));
21 25
22vi.mock("@1password/op-js", () => ({26vi.mock("@1password/op-js", () => ({
@@ -27,10 +31,7 @@ vi.mock("@1password/op-js", () => ({ · 4 unmodified lines
27 read: { parse: opMocks.readParse },31 read: { parse: opMocks.readParse },
28}));32}));
29 33
30vi.mock("@1password/sdk", () => ({34vi.mock("@1password/sdk", () => sdkMocks.exports);
31 createClient: sdkMocks.createClient,
32 DesktopAuth: sdkMocks.DesktopAuth,
33}));
34 35
35describe("makeOnePasswordService", () => {36describe("makeOnePasswordService", () => {
36 beforeEach(() => {37 beforeEach(() => {
@@ -38,6 +39,8 @@ describe("makeOnePasswordService", () => { · 1 unmodified line
38 opMocks.vaultList.mockReturnValue([]);39 opMocks.vaultList.mockReturnValue([]);
39 opMocks.itemList.mockReturnValue([]);40 opMocks.itemList.mockReturnValue([]);
40 opMocks.readParse.mockReturnValue("secret");41 opMocks.readParse.mockReturnValue("secret");
42 sdkMocks.exports.createClient = sdkMocks.createClient;
43 sdkMocks.exports.DesktopAuth = sdkMocks.DesktopAuth;
41 sdkMocks.createClient.mockResolvedValue({44 sdkMocks.createClient.mockResolvedValue({
42 secrets: { resolve: vi.fn(async () => "secret") },45 secrets: { resolve: vi.fn(async () => "secret") },
43 vaults: { list: vi.fn(async () => []) },46 vaults: { list: vi.fn(async () => []) },
@@ -103,4 +106,30 @@ describe("makeOnePasswordService", () => { · 59 unmodified lines
103 // oxlint-enable executor/no-unknown-error-message106 // oxlint-enable executor/no-unknown-error-message
104 }),107 }),
105 );108 );
109
110 it.effect("reports a clear SDK load error when the compiled namespace is empty", () =>
111 Effect.gen(function* () {
112 opMocks.vaultList.mockImplementation(() => {
113 // oxlint-disable-next-line executor/no-try-catch-or-throw, executor/no-error-constructor -- boundary: simulates the untyped op-js CLI wrapper throwing
114 throw new Error("spawn op ENOENT");
115 });
116 sdkMocks.exports.createClient = undefined;
117 sdkMocks.exports.DesktopAuth = undefined;
118
119 const error = yield* makeOnePasswordService(
120 { kind: "service-account", token: "ops_test_token" },
121 { timeoutMs: 1_000 },
122 ).pipe(
123 Effect.flatMap((service) => service.listVaults()),
124 Effect.flip,
125 );
126
127 expect(error).toBeInstanceOf(OnePasswordError);
128 expect(error.operation).toBe("sdk module load");
129 // oxlint-disable executor/no-unknown-error-message -- boundary: OnePasswordError carries a typed message; asserting its contents
130 expect(error.message).toContain("did not expose createClient and DesktopAuth");
131 expect(error.message).toContain("/opt/homebrew/bin");
132 // oxlint-enable executor/no-unknown-error-message
133 }),
134 );
106});135});
packages/plugins/onepassword/src/sdk/service.ts+21−3
@@ -2,6 +2,7 @@ import { Context, Duration, Effect, Semaphore } from "effect"; · 1 unmodified line
2import * as op from "@1password/op-js";2import * as op from "@1password/op-js";
3 3
4import { OnePasswordError } from "./errors";4import { OnePasswordError } from "./errors";
5import type { OnePasswordSdkModule } from "./onepassword-sdk";
5 6
6// ---------------------------------------------------------------------------7// ---------------------------------------------------------------------------
7// Canonical service interface — all backends (SDK, CLI) implement this8// Canonical service interface — all backends (SDK, CLI) implement this
@@ -50,7 +51,6 @@ export type ResolvedAuth = · 42 unmodified lines
50const DEFAULT_TIMEOUT_MS = 15_000;51const DEFAULT_TIMEOUT_MS = 15_000;
51const MAX_ERROR_MESSAGE_LENGTH = 300;52const MAX_ERROR_MESSAGE_LENGTH = 300;
52const SERVICE_ACCOUNT_TOKEN_RE = /ops_[A-Za-z0-9_-]+/g;53const SERVICE_ACCOUNT_TOKEN_RE = /ops_[A-Za-z0-9_-]+/g;
53type OnePasswordSdkModule = typeof import("@1password/sdk");
54 54
55const formatCause = (cause: unknown): string => {55const formatCause = (cause: unknown): string => {
56 // oxlint-disable-next-line executor/no-unknown-error-message -- boundary: normalizing untyped op-js/SDK throwables into OnePasswordError.message56 // oxlint-disable-next-line executor/no-unknown-error-message -- boundary: normalizing untyped op-js/SDK throwables into OnePasswordError.message
@@ -72,15 +72,33 @@ const messageWithCause = (prefix: string, cause: unknown): string => { · 15 unmodified lines
72 : message;72 : message;
73};73};
74 74
75const hasOnePasswordSdkShape = (value: unknown): value is OnePasswordSdkModule => {
76 const sdk = value as Partial<OnePasswordSdkModule> | null | undefined;
77 return typeof sdk?.createClient === "function" && typeof sdk.DesktopAuth === "function";
78};
79
80const invalidOnePasswordSdkError = () =>
81 new OnePasswordError({
82 operation: "sdk module load",
83 message: [
84 "Failed to load 1Password SDK: the packaged SDK module did not expose createClient and DesktopAuth.",
85 "Install the 1Password CLI (`op`) in /opt/homebrew/bin or /usr/local/bin and retry, or update Executor.",
86 ].join(" "),
87 });
88
75const loadOnePasswordSdk = (): Effect.Effect<OnePasswordSdkModule, OnePasswordError> =>89const loadOnePasswordSdk = (): Effect.Effect<OnePasswordSdkModule, OnePasswordError> =>
76 Effect.tryPromise({90 Effect.tryPromise({
77 try: () => import("@1password/sdk"),91 try: () => import("./onepassword-sdk").then((module) => module.onePasswordSdk),
78 catch: (cause) =>92 catch: (cause) =>
79 new OnePasswordError({93 new OnePasswordError({
80 operation: "sdk module load",94 operation: "sdk module load",
81 message: messageWithCause("Failed to load 1Password SDK", cause),95 message: messageWithCause("Failed to load 1Password SDK", cause),
82 }),96 }),
83 });97 }).pipe(
98 Effect.flatMap((sdk) =>
99 hasOnePasswordSdkShape(sdk) ? Effect.succeed(sdk) : Effect.fail(invalidOnePasswordSdkError()),
100 ),
101 );
84 102
85const makeTimeoutMessage = (operation: string, timeoutMs: number): string =>103const makeTimeoutMessage = (operation: string, timeoutMs: number): string =>
86 [104 [
patches/@1password%2Fsdk-core@0.4.1-beta.1.patch+24−0
@@ -0,0 +1,24 @@
1diff --git a/nodejs/core.js b/nodejs/core.js
2index 259891a2bbcd97e6630855087547fb1b5a389876..768a8321cbf31212e5a31b075d44706803a362a8 100644
3--- a/nodejs/core.js
4+++ b/nodejs/core.js
5@@ -786,8 +786,17 @@ module.exports.__wbindgen_throw = function(arg0, arg1) {
6 throw new Error(getStringFromWasm0(arg0, arg1));
7 };
8
9-const path = require('path').join(__dirname, 'core_bg.wasm');
10-const bytes = require('fs').readFileSync(path);
11+const path = require('path');
12+const fs = require('fs');
13+const wasmPath = path.join(__dirname, 'core_bg.wasm');
14+let bytes;
15+try {
16+ bytes = fs.readFileSync(wasmPath);
17+} catch {
18+ bytes = fs.readFileSync(
19+ path.join(path.dirname(process.execPath), 'onepassword-core_bg.wasm'),
20+ );
21+}
22
23 const wasmModule = new WebAssembly.Module(bytes);
24 const wasmInstance = new WebAssembly.Instance(wasmModule, imports);

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t