@sohopay/agent-signer 0.0.0-stage → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +261 -2
- package/dist/cli/args.d.ts +20 -0
- package/dist/cli/args.js +106 -0
- package/dist/cli/commands.d.ts +37 -0
- package/dist/cli/commands.js +230 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +32 -0
- package/dist/cli/io-schema.d.ts +2 -0
- package/dist/cli/io-schema.js +55 -0
- package/dist/cli/io.d.ts +18 -0
- package/dist/cli/io.js +56 -0
- package/dist/cli/key-generate.d.ts +8 -0
- package/dist/cli/key-generate.js +77 -0
- package/dist/cli/key-path.d.ts +15 -0
- package/dist/cli/key-path.js +188 -0
- package/dist/cli/node-floor.d.ts +4 -0
- package/dist/cli/node-floor.js +11 -0
- package/dist/cli/run.d.ts +11 -0
- package/dist/cli/run.js +148 -0
- package/dist/cli/signer-config.d.ts +6 -0
- package/dist/cli/signer-config.js +84 -0
- package/dist/cli/verify-vectors.d.ts +8 -0
- package/dist/cli/verify-vectors.js +116 -0
- package/dist/constants.d.ts +24 -0
- package/dist/constants.js +34 -0
- package/dist/encoding.d.ts +5 -0
- package/dist/encoding.js +5 -0
- package/dist/envelope.d.ts +11 -0
- package/dist/envelope.js +20 -0
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +9 -0
- package/dist/flow.d.ts +70 -0
- package/dist/flow.js +62 -0
- package/dist/idempotency.d.ts +32 -0
- package/dist/idempotency.js +45 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +12 -0
- package/dist/jcs.d.ts +8 -0
- package/dist/jcs.js +15 -0
- package/dist/keys.d.ts +28 -0
- package/dist/keys.js +64 -0
- package/dist/operations.d.ts +107 -0
- package/dist/operations.js +151 -0
- package/dist/pop.d.ts +19 -0
- package/dist/pop.js +27 -0
- package/dist/rotation.d.ts +41 -0
- package/dist/rotation.js +33 -0
- package/dist/storage.d.ts +38 -0
- package/dist/storage.js +116 -0
- package/dist/terminal.d.ts +31 -0
- package/dist/terminal.js +142 -0
- package/dist/voucher.d.ts +39 -0
- package/dist/voucher.js +86 -0
- package/package.json +37 -4
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { assertNodeFloor } from "./node-floor.js";
|
|
3
|
+
// ESM hoists static imports, so only the guard is imported statically; everything that may
|
|
4
|
+
// touch Node-18-only APIs is loaded dynamically after the check.
|
|
5
|
+
try {
|
|
6
|
+
assertNodeFloor(process.versions.node);
|
|
7
|
+
}
|
|
8
|
+
catch (e) {
|
|
9
|
+
const code = e.code ?? "NODE_VERSION_UNSUPPORTED";
|
|
10
|
+
process.stderr.write(JSON.stringify({ error: { code, message: e.message } }) + "\n");
|
|
11
|
+
process.exit(1);
|
|
12
|
+
}
|
|
13
|
+
const { readFileSync } = await import("node:fs");
|
|
14
|
+
const { needsStdin } = await import("./args.js");
|
|
15
|
+
const { run } = await import("./run.js");
|
|
16
|
+
/** Reads all of stdin synchronously (fd 0). Empty string when nothing is piped. */
|
|
17
|
+
function readStdin() {
|
|
18
|
+
try {
|
|
19
|
+
return readFileSync(0, "utf8");
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return "";
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
const argv = process.argv.slice(2);
|
|
26
|
+
const stdin = needsStdin(argv) ? readStdin() : "";
|
|
27
|
+
const result = run(argv, stdin);
|
|
28
|
+
if (result.stdout)
|
|
29
|
+
process.stdout.write(result.stdout);
|
|
30
|
+
if (result.stderr)
|
|
31
|
+
process.stderr.write(result.stderr);
|
|
32
|
+
process.exitCode = result.exitCode;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { SignerError } from "../errors.js";
|
|
2
|
+
const INPUT_ALLOW = {
|
|
3
|
+
"pop sign": { top: ["fields"], fields: ["borrowerId", "terminalId", "jkt"] },
|
|
4
|
+
"key generate": { top: ["borrower_id", "terminal_id"] },
|
|
5
|
+
};
|
|
6
|
+
const OUTPUT_ALLOW = {
|
|
7
|
+
"key generate": ["public_jwk", "jkt", "borrower_id", "terminal_id", "created"],
|
|
8
|
+
"pop sign": ["signer_protocol", "implementation", "implementation_version", "pop_signature", "nonce", "iat", "algorithm"],
|
|
9
|
+
};
|
|
10
|
+
function keysOutside(obj, allow) {
|
|
11
|
+
return Object.keys(obj).filter((k) => !allow.includes(k));
|
|
12
|
+
}
|
|
13
|
+
export function assertInputSchema(command, input) {
|
|
14
|
+
const spec = INPUT_ALLOW[command];
|
|
15
|
+
if (!spec)
|
|
16
|
+
return;
|
|
17
|
+
if (input === null || typeof input !== "object" || Array.isArray(input)) {
|
|
18
|
+
throw new SignerError("MALFORMED_INPUT", `${command} input must be an object`);
|
|
19
|
+
}
|
|
20
|
+
const rec = input;
|
|
21
|
+
const extraTop = keysOutside(rec, spec.top);
|
|
22
|
+
if (extraTop.length > 0) {
|
|
23
|
+
throw new SignerError("MALFORMED_INPUT", `${command}: unexpected input field(s): ${extraTop.join(", ")}`);
|
|
24
|
+
}
|
|
25
|
+
if (spec.fields) {
|
|
26
|
+
const fields = rec.fields;
|
|
27
|
+
if (fields === null || typeof fields !== "object" || Array.isArray(fields)) {
|
|
28
|
+
throw new SignerError("MALFORMED_INPUT", `${command} requires a \`fields\` object`);
|
|
29
|
+
}
|
|
30
|
+
const extra = keysOutside(fields, spec.fields);
|
|
31
|
+
if (extra.length > 0) {
|
|
32
|
+
throw new SignerError("MALFORMED_INPUT", `${command}: unexpected field(s): ${extra.join(", ")}`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export function assertOutputSchema(command, output) {
|
|
37
|
+
const allow = OUTPUT_ALLOW[command];
|
|
38
|
+
if (!allow)
|
|
39
|
+
return;
|
|
40
|
+
const extra = keysOutside(output, allow);
|
|
41
|
+
if (extra.length > 0) {
|
|
42
|
+
throw new Error(`internal: ${command} output leaked field(s): ${extra.join(", ")}`);
|
|
43
|
+
}
|
|
44
|
+
// Validate public_jwk contents: only kty, crv, x allowed
|
|
45
|
+
if (output.public_jwk !== undefined) {
|
|
46
|
+
const jwk = output.public_jwk;
|
|
47
|
+
if (jwk === null || typeof jwk !== "object" || Array.isArray(jwk)) {
|
|
48
|
+
throw new Error(`internal: ${command} public_jwk must be an object`);
|
|
49
|
+
}
|
|
50
|
+
const jwkKeys = keysOutside(jwk, ["kty", "crv", "x"]);
|
|
51
|
+
if (jwkKeys.length > 0) {
|
|
52
|
+
throw new Error(`internal: ${command} public_jwk leaked field(s): ${jwkKeys.join(", ")}`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
package/dist/cli/io.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type Ed25519PublicJwk } from "../keys.js";
|
|
2
|
+
/** A key block coerced to the SDK's camelCase argument names. */
|
|
3
|
+
export interface ResolvedKey {
|
|
4
|
+
privateKeyBase64Url?: string;
|
|
5
|
+
publicJwk?: Ed25519PublicJwk;
|
|
6
|
+
}
|
|
7
|
+
/** Reads and JSON-parses the --input source. Absence is a usage error (exit 2). */
|
|
8
|
+
export declare function readInput(source: string | undefined, stdin: string): unknown;
|
|
9
|
+
/**
|
|
10
|
+
* Coerces an on-wire key block ({ private_key_base64url?, public_jwk? }) to the
|
|
11
|
+
* SDK's camelCase names. `public_jwk` is validated by the SDK (rejects `d`).
|
|
12
|
+
*/
|
|
13
|
+
export declare function resolveKeyBlock(block: unknown): ResolvedKey;
|
|
14
|
+
/** Reads a validated key file path (allowed root, 0600, no symlinks) into a ResolvedKey. */
|
|
15
|
+
export declare function readKeyFile(source: string, _stdin: string, opts?: {
|
|
16
|
+
homeDir?: string;
|
|
17
|
+
env?: NodeJS.ProcessEnv;
|
|
18
|
+
}): ResolvedKey;
|
package/dist/cli/io.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { UsageError } from "./args.js";
|
|
3
|
+
import { SignerError } from "../errors.js";
|
|
4
|
+
import { assertPublicJwk } from "../keys.js";
|
|
5
|
+
import { loadKeyFile } from "../storage.js";
|
|
6
|
+
import { validateKeyPath } from "./key-path.js";
|
|
7
|
+
/** Reads and JSON-parses the --input source. Absence is a usage error (exit 2). */
|
|
8
|
+
export function readInput(source, stdin) {
|
|
9
|
+
if (source === undefined) {
|
|
10
|
+
throw new UsageError("this command requires --input <file|->");
|
|
11
|
+
}
|
|
12
|
+
let raw;
|
|
13
|
+
if (source === "-") {
|
|
14
|
+
raw = stdin;
|
|
15
|
+
}
|
|
16
|
+
else {
|
|
17
|
+
try {
|
|
18
|
+
raw = readFileSync(source, "utf8");
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
throw new SignerError("MALFORMED_ENVELOPE", `cannot read input file: ${source}`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
try {
|
|
25
|
+
return JSON.parse(raw);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
throw new SignerError("MALFORMED_ENVELOPE", "input is not valid JSON");
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Coerces an on-wire key block ({ private_key_base64url?, public_jwk? }) to the
|
|
33
|
+
* SDK's camelCase names. `public_jwk` is validated by the SDK (rejects `d`).
|
|
34
|
+
*/
|
|
35
|
+
export function resolveKeyBlock(block) {
|
|
36
|
+
if (block === null || typeof block !== "object") {
|
|
37
|
+
throw new SignerError("MALFORMED_ENVELOPE", "key block must be an object");
|
|
38
|
+
}
|
|
39
|
+
const record = block;
|
|
40
|
+
const resolved = {};
|
|
41
|
+
const priv = record.private_key_base64url;
|
|
42
|
+
if (priv !== undefined) {
|
|
43
|
+
if (typeof priv !== "string") {
|
|
44
|
+
throw new SignerError("MALFORMED_ENVELOPE", "private_key_base64url must be a string");
|
|
45
|
+
}
|
|
46
|
+
resolved.privateKeyBase64Url = priv;
|
|
47
|
+
}
|
|
48
|
+
if (record.public_jwk !== undefined) {
|
|
49
|
+
resolved.publicJwk = assertPublicJwk(record.public_jwk);
|
|
50
|
+
}
|
|
51
|
+
return resolved;
|
|
52
|
+
}
|
|
53
|
+
/** Reads a validated key file path (allowed root, 0600, no symlinks) into a ResolvedKey. */
|
|
54
|
+
export function readKeyFile(source, _stdin, opts = {}) {
|
|
55
|
+
return resolveKeyBlock(loadKeyFile(validateKeyPath(source, "read", opts)));
|
|
56
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ensure-mode key generation + persistence. Never overwrites an existing key:
|
|
3
|
+
* an existing file is only verified (borrower, terminal, derived-public integrity).
|
|
4
|
+
*/
|
|
5
|
+
export declare function keyGenerateResult(input: unknown, outPath: string | undefined, opts?: {
|
|
6
|
+
homeDir?: string;
|
|
7
|
+
env?: NodeJS.ProcessEnv;
|
|
8
|
+
}): Record<string, unknown>;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { closeSync, openSync } from "node:fs";
|
|
2
|
+
import { SignerError } from "../errors.js";
|
|
3
|
+
import { generateWorkloadKey, workloadKeyFromPrivate } from "../keys.js";
|
|
4
|
+
import { loadKeyFile, writeSecretFileAtPath } from "../storage.js";
|
|
5
|
+
import { validateKeyPath } from "./key-path.js";
|
|
6
|
+
function str(rec, k) {
|
|
7
|
+
const v = rec[k];
|
|
8
|
+
if (typeof v !== "string" || v.length === 0) {
|
|
9
|
+
throw new SignerError("MALFORMED_INPUT", `key generate requires a non-empty string \`${k}\``);
|
|
10
|
+
}
|
|
11
|
+
return v;
|
|
12
|
+
}
|
|
13
|
+
/** Public-only projection; the private key must never leave this module. */
|
|
14
|
+
function publicMaterial(stored) {
|
|
15
|
+
return { public_jwk: stored.public_jwk, jkt: stored.jkt, borrower_id: stored.borrower_id, terminal_id: stored.terminal_id };
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Ensure-mode key generation + persistence. Never overwrites an existing key:
|
|
19
|
+
* an existing file is only verified (borrower, terminal, derived-public integrity).
|
|
20
|
+
*/
|
|
21
|
+
export function keyGenerateResult(input, outPath, opts = {}) {
|
|
22
|
+
if (outPath === undefined) {
|
|
23
|
+
throw new SignerError("MALFORMED_INPUT", "key generate requires --out <path>");
|
|
24
|
+
}
|
|
25
|
+
const rec = (input ?? {});
|
|
26
|
+
const borrowerId = str(rec, "borrower_id");
|
|
27
|
+
const terminalId = str(rec, "terminal_id");
|
|
28
|
+
// Probe existence via a read-mode validation (throws KEY_PATH_INVALID when absent).
|
|
29
|
+
let existing;
|
|
30
|
+
try {
|
|
31
|
+
existing = loadKeyFile(validateKeyPath(outPath, "read", opts));
|
|
32
|
+
}
|
|
33
|
+
catch (e) {
|
|
34
|
+
if (e.code !== "KEY_PATH_INVALID")
|
|
35
|
+
throw e;
|
|
36
|
+
existing = undefined;
|
|
37
|
+
}
|
|
38
|
+
if (existing) {
|
|
39
|
+
if (existing.borrower_id !== borrowerId) {
|
|
40
|
+
throw new SignerError("CROSS_BORROWER_KEY", "a key for a different borrower exists at this path");
|
|
41
|
+
}
|
|
42
|
+
if (existing.terminal_id !== terminalId) {
|
|
43
|
+
throw new SignerError("TERMINAL_MISMATCH", "the stored key is bound to a different terminal");
|
|
44
|
+
}
|
|
45
|
+
const derived = workloadKeyFromPrivate(existing.private_key_base64url);
|
|
46
|
+
if (derived.jkt !== existing.jkt || derived.publicJwk.x !== existing.public_jwk.x) {
|
|
47
|
+
throw new SignerError("KEY_INTEGRITY_FAILED", "stored public material does not match the private key");
|
|
48
|
+
}
|
|
49
|
+
return { ...publicMaterial(existing), created: false };
|
|
50
|
+
}
|
|
51
|
+
const writePath = validateKeyPath(outPath, "ensure", opts); // re-checks nothing exists (race)
|
|
52
|
+
const keypair = generateWorkloadKey();
|
|
53
|
+
const stored = {
|
|
54
|
+
private_key_base64url: keypair.privateKeyBase64Url,
|
|
55
|
+
public_jwk: keypair.publicJwk,
|
|
56
|
+
jkt: keypair.jkt,
|
|
57
|
+
terminal_id: terminalId,
|
|
58
|
+
borrower_id: borrowerId,
|
|
59
|
+
};
|
|
60
|
+
try {
|
|
61
|
+
// O_EXCL placeholder claims the path; a race loser re-enters the read branch.
|
|
62
|
+
closeSync(openSync(writePath, "wx", 0o600));
|
|
63
|
+
}
|
|
64
|
+
catch (e) {
|
|
65
|
+
if (e.code === "EEXIST") {
|
|
66
|
+
return keyGenerateResult(input, outPath, opts);
|
|
67
|
+
}
|
|
68
|
+
throw new SignerError("KEY_PERSIST_FAILED", `cannot create ${writePath}`);
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
writeSecretFileAtPath(writePath, stored); // atomic rename over the placeholder
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
throw new SignerError("KEY_PERSIST_FAILED", "cannot persist the workload key");
|
|
75
|
+
}
|
|
76
|
+
return { ...publicMaterial(stored), created: true };
|
|
77
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Validate a key path for `read` or `ensure`, returning the absolute path. */
|
|
2
|
+
export declare function validateKeyPath(path: string, mode: "read" | "ensure", opts?: {
|
|
3
|
+
homeDir?: string;
|
|
4
|
+
env?: NodeJS.ProcessEnv;
|
|
5
|
+
}): string;
|
|
6
|
+
/**
|
|
7
|
+
* `--terminal <id>` -> `<default root>/<sha256-hex(id)>/secret.json`. The raw id
|
|
8
|
+
* (`:`, `@`, `..`) never reaches the filesystem; only its digest names the folder.
|
|
9
|
+
* Ensure mode creates that one 0700 folder (and an absent root); the returned path
|
|
10
|
+
* still goes through {@link validateKeyPath}, so every existing check applies.
|
|
11
|
+
*/
|
|
12
|
+
export declare function terminalKeyPath(terminalId: string, mode: "read" | "ensure", opts?: {
|
|
13
|
+
homeDir?: string;
|
|
14
|
+
env?: NodeJS.ProcessEnv;
|
|
15
|
+
}): string;
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { lstatSync, mkdirSync, realpathSync, statSync } from "node:fs";
|
|
3
|
+
import { homedir, platform, userInfo } from "node:os";
|
|
4
|
+
import { basename, dirname, join, resolve, sep } from "node:path";
|
|
5
|
+
import { SignerError } from "../errors.js";
|
|
6
|
+
import { assertValidTerminalId } from "../terminal.js";
|
|
7
|
+
import { DEFAULT_SUBDIR, resolveKeyRoots } from "./signer-config.js";
|
|
8
|
+
function invalid(message) {
|
|
9
|
+
throw new SignerError("KEY_PATH_INVALID", message);
|
|
10
|
+
}
|
|
11
|
+
/** lstat never follows links, so a dangling symlink is still reported; only ENOENT means absent. */
|
|
12
|
+
function lstatOrNull(path) {
|
|
13
|
+
try {
|
|
14
|
+
return lstatSync(path);
|
|
15
|
+
}
|
|
16
|
+
catch (err) {
|
|
17
|
+
if (err.code === "ENOENT")
|
|
18
|
+
return null;
|
|
19
|
+
return invalid(`cannot inspect ${path}`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/** No symlink and no `..` from the root down to the target (existing components only). */
|
|
23
|
+
function assertNoSymlinkBelow(root, target) {
|
|
24
|
+
if (platform() === "win32")
|
|
25
|
+
return;
|
|
26
|
+
if (target !== root && !target.startsWith(root + sep))
|
|
27
|
+
invalid(`${target} is not under ${root}`);
|
|
28
|
+
const rest = target.slice(root.length).split(sep).filter((s) => s.length > 0);
|
|
29
|
+
let cur = root;
|
|
30
|
+
for (const seg of rest) {
|
|
31
|
+
if (seg === "..")
|
|
32
|
+
invalid("path must not contain ..");
|
|
33
|
+
cur = cur + sep + seg;
|
|
34
|
+
const st = lstatOrNull(cur);
|
|
35
|
+
if (st === null)
|
|
36
|
+
return; // genuinely absent: nothing below it exists either
|
|
37
|
+
if (st.isSymbolicLink())
|
|
38
|
+
invalid(`${cur} is a symlink`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** Realpath, or null when the path is absent or unreadable. */
|
|
42
|
+
function realOrNull(p) {
|
|
43
|
+
try {
|
|
44
|
+
return realpathSync(p);
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Ensure-mode "mkdir parent 0700 if missing": create an absent allowed root (and any
|
|
52
|
+
* missing ancestors) at 0700, owner-only. The deepest already-existing ancestor must be
|
|
53
|
+
* a real directory, never a symlink; every component we create is made by us, so it
|
|
54
|
+
* cannot be a symlink. Runs only after the path has been placed under an allowed root,
|
|
55
|
+
* and never creates a subdirectory *below* the root (a missing nested dir still fails
|
|
56
|
+
* the parent-mode check, as before).
|
|
57
|
+
*/
|
|
58
|
+
function ensureRootExists(root) {
|
|
59
|
+
if (platform() === "win32") {
|
|
60
|
+
try {
|
|
61
|
+
mkdirSync(root, { recursive: true });
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
invalid(`cannot create ${root}`);
|
|
65
|
+
}
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
if (lstatOrNull(root) !== null)
|
|
69
|
+
return; // already present (symlinked-root handling is unchanged)
|
|
70
|
+
const missing = [];
|
|
71
|
+
let cur = root;
|
|
72
|
+
while (lstatOrNull(cur) === null) {
|
|
73
|
+
missing.unshift(cur);
|
|
74
|
+
const parent = dirname(cur);
|
|
75
|
+
if (parent === cur)
|
|
76
|
+
break; // reached the filesystem root
|
|
77
|
+
cur = parent;
|
|
78
|
+
}
|
|
79
|
+
const anchor = lstatOrNull(cur);
|
|
80
|
+
if (anchor === null || anchor.isSymbolicLink() || !anchor.isDirectory()) {
|
|
81
|
+
invalid(`${cur} is not a usable parent directory`);
|
|
82
|
+
}
|
|
83
|
+
for (const dir of missing) {
|
|
84
|
+
try {
|
|
85
|
+
mkdirSync(dir, { mode: 0o700 });
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
invalid(`cannot create ${dir}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function assertOwnerMode(path, denyMask) {
|
|
93
|
+
if (platform() === "win32")
|
|
94
|
+
return;
|
|
95
|
+
let st;
|
|
96
|
+
try {
|
|
97
|
+
st = statSync(path);
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return invalid(`${path} cannot be inspected (missing or unreadable)`);
|
|
101
|
+
}
|
|
102
|
+
if (st.uid !== userInfo().uid)
|
|
103
|
+
invalid(`${path} is not owned by the current user`);
|
|
104
|
+
if ((st.mode & denyMask) !== 0)
|
|
105
|
+
invalid(`${path} has too-permissive mode`);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Locate the allowed root containing `abs`. Roots are realpath-resolved, so the
|
|
109
|
+
* lexical prefix of `abs` (e.g. macOS /var -> /private/var) is matched through its
|
|
110
|
+
* realpath; the remainder below the root stays unresolved so symlinks there are caught.
|
|
111
|
+
*/
|
|
112
|
+
function locateRoot(abs, roots) {
|
|
113
|
+
for (let anc = abs;; anc = dirname(anc)) {
|
|
114
|
+
const real = realOrNull(anc);
|
|
115
|
+
if (real !== null && roots.includes(real))
|
|
116
|
+
return { root: real, canonical: real + abs.slice(anc.length) };
|
|
117
|
+
if (dirname(anc) === anc)
|
|
118
|
+
break;
|
|
119
|
+
}
|
|
120
|
+
// Fallback for a configured root that does not yet exist on disk (fresh machine):
|
|
121
|
+
// match lexically so ensure mode can create it. Only absent roots qualify, so this
|
|
122
|
+
// never widens acceptance for an existing (possibly symlinked) root, which the
|
|
123
|
+
// realpath walk above already resolves.
|
|
124
|
+
for (const r of roots) {
|
|
125
|
+
if (realOrNull(r) !== null)
|
|
126
|
+
continue;
|
|
127
|
+
if (abs === r || abs.startsWith(r + sep))
|
|
128
|
+
return { root: r, canonical: abs };
|
|
129
|
+
}
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
/** Validate a key path for `read` or `ensure`, returning the absolute path. */
|
|
133
|
+
export function validateKeyPath(path, mode, opts = {}) {
|
|
134
|
+
const abs = resolve(path);
|
|
135
|
+
if (basename(abs) !== "secret.json")
|
|
136
|
+
invalid("key file must be named secret.json");
|
|
137
|
+
const roots = resolveKeyRoots(opts);
|
|
138
|
+
const found = locateRoot(abs, roots);
|
|
139
|
+
if (!found)
|
|
140
|
+
invalid(`${abs} is not under an allowed key root`);
|
|
141
|
+
const { root } = found;
|
|
142
|
+
const target = found.canonical;
|
|
143
|
+
// Ensure mode provisions an absent allowed root (never a nested subdir below it), so a
|
|
144
|
+
// fresh machine can create its first key — the spec's "mkdir parent 0700 if missing".
|
|
145
|
+
if (mode === "ensure")
|
|
146
|
+
ensureRootExists(root);
|
|
147
|
+
assertNoSymlinkBelow(root, target);
|
|
148
|
+
assertOwnerMode(dirname(target), 0o077); // parent dir 0700, owner
|
|
149
|
+
if (mode === "read") {
|
|
150
|
+
if (lstatOrNull(target) === null)
|
|
151
|
+
invalid(`${target} does not exist`);
|
|
152
|
+
assertOwnerMode(target, 0o077); // file 0600, owner
|
|
153
|
+
}
|
|
154
|
+
else if (lstatOrNull(target) !== null) {
|
|
155
|
+
invalid(`${target} already exists (ensure mode never overwrites)`);
|
|
156
|
+
}
|
|
157
|
+
return target;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* `--terminal <id>` -> `<default root>/<sha256-hex(id)>/secret.json`. The raw id
|
|
161
|
+
* (`:`, `@`, `..`) never reaches the filesystem; only its digest names the folder.
|
|
162
|
+
* Ensure mode creates that one 0700 folder (and an absent root); the returned path
|
|
163
|
+
* still goes through {@link validateKeyPath}, so every existing check applies.
|
|
164
|
+
*/
|
|
165
|
+
export function terminalKeyPath(terminalId, mode, opts = {}) {
|
|
166
|
+
const id = assertValidTerminalId(terminalId);
|
|
167
|
+
// The digest already keeps `..` off disk; refuse it anyway so a traversal-shaped id fails loudly.
|
|
168
|
+
if (id.includes(".."))
|
|
169
|
+
invalid("terminal id must not contain ..");
|
|
170
|
+
const digest = createHash("sha256").update(id, "utf8").digest("hex");
|
|
171
|
+
const file = join(opts.homeDir ?? homedir(), ...DEFAULT_SUBDIR, digest, "secret.json");
|
|
172
|
+
if (mode === "ensure") {
|
|
173
|
+
const found = locateRoot(file, resolveKeyRoots(opts));
|
|
174
|
+
if (!found)
|
|
175
|
+
invalid(`${file} is not under an allowed key root`);
|
|
176
|
+
ensureRootExists(found.root);
|
|
177
|
+
const dir = dirname(found.canonical);
|
|
178
|
+
assertNoSymlinkBelow(found.root, dir);
|
|
179
|
+
try {
|
|
180
|
+
mkdirSync(dir, { mode: 0o700 });
|
|
181
|
+
}
|
|
182
|
+
catch (err) {
|
|
183
|
+
if (err.code !== "EEXIST")
|
|
184
|
+
invalid(`cannot create ${dir}`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return file;
|
|
188
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Minimum Node major this signer runs on. Mirrors package.json "engines". */
|
|
2
|
+
export const MIN_NODE_MAJOR = 18;
|
|
3
|
+
/** Throws a coded error if the runtime Node major is below the floor. */
|
|
4
|
+
export function assertNodeFloor(nodeVersion) {
|
|
5
|
+
const major = Number.parseInt((nodeVersion.split(".")[0] ?? "").trim(), 10);
|
|
6
|
+
if (!Number.isFinite(major) || major < MIN_NODE_MAJOR) {
|
|
7
|
+
const err = new Error(`sohopay-signer requires Node >= ${MIN_NODE_MAJOR}`);
|
|
8
|
+
err.code = "NODE_VERSION_UNSUPPORTED";
|
|
9
|
+
throw err;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface CliResult {
|
|
2
|
+
stdout: string;
|
|
3
|
+
stderr: string;
|
|
4
|
+
exitCode: number;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Pure orchestrator: parse → dispatch → format. Never throws; every failure is
|
|
8
|
+
* mapped to a CliResult. Usage errors exit 2 (plain stderr); SignerError and
|
|
9
|
+
* other operational failures exit 1 with a machine error envelope on stderr.
|
|
10
|
+
*/
|
|
11
|
+
export declare function run(argv: string[], stdin: string): CliResult;
|
package/dist/cli/run.js
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { chmodSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { parseArgs, UsageError } from "./args.js";
|
|
3
|
+
import { capabilitiesResult, keyJktResult, paymentIdResult, popSignResult, verifyVectorsResult, voucherSignEnvelopeResult, voucherSignResult } from "./commands.js";
|
|
4
|
+
import { readInput } from "./io.js";
|
|
5
|
+
import { assertInputSchema, assertOutputSchema } from "./io-schema.js";
|
|
6
|
+
import { keyGenerateResult } from "./key-generate.js";
|
|
7
|
+
import { terminalKeyPath } from "./key-path.js";
|
|
8
|
+
import { SignerError } from "../errors.js";
|
|
9
|
+
import { resolveHarnessTerminalId } from "../terminal.js";
|
|
10
|
+
const TERMINAL_COMMANDS = new Set(["key generate", "pop sign", "voucher sign"]);
|
|
11
|
+
/** Renders a result object as human-readable `key: value` lines (never secrets). */
|
|
12
|
+
function toHuman(result) {
|
|
13
|
+
return (Object.entries(result)
|
|
14
|
+
.map(([k, v]) => `${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`)
|
|
15
|
+
.join("\n") + "\n");
|
|
16
|
+
}
|
|
17
|
+
function format(result, output) {
|
|
18
|
+
return output === "json" ? JSON.stringify(result) : toHuman(result);
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Pure orchestrator: parse → dispatch → format. Never throws; every failure is
|
|
22
|
+
* mapped to a CliResult. Usage errors exit 2 (plain stderr); SignerError and
|
|
23
|
+
* other operational failures exit 1 with a machine error envelope on stderr.
|
|
24
|
+
*/
|
|
25
|
+
export function run(argv, stdin) {
|
|
26
|
+
try {
|
|
27
|
+
const parsed = parseArgs(argv);
|
|
28
|
+
if (parsed.input === "-" && parsed.key === "-") {
|
|
29
|
+
throw new UsageError("--input and --key cannot both read stdin");
|
|
30
|
+
}
|
|
31
|
+
if ((parsed.envelope || parsed.writeHeader !== undefined) && parsed.command !== "voucher sign") {
|
|
32
|
+
throw new UsageError("--envelope and --write-header are only valid for `voucher sign`");
|
|
33
|
+
}
|
|
34
|
+
if (parsed.writeHeader !== undefined && !parsed.envelope) {
|
|
35
|
+
throw new UsageError("--write-header requires --envelope");
|
|
36
|
+
}
|
|
37
|
+
if (parsed.harness !== undefined && parsed.command !== "terminal id") {
|
|
38
|
+
throw new UsageError("--harness is only valid for `terminal id`");
|
|
39
|
+
}
|
|
40
|
+
if (parsed.terminal !== undefined) {
|
|
41
|
+
if (!TERMINAL_COMMANDS.has(parsed.command)) {
|
|
42
|
+
throw new UsageError("--terminal is only valid for `key generate`, `pop sign` and `voucher sign`");
|
|
43
|
+
}
|
|
44
|
+
if (parsed.key !== undefined || parsed.out !== undefined) {
|
|
45
|
+
throw new UsageError("--terminal replaces --key / --out; pass only one");
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const terminalKey = parsed.terminal !== undefined && parsed.command !== "key generate"
|
|
49
|
+
? terminalKeyPath(parsed.terminal, "read")
|
|
50
|
+
: undefined;
|
|
51
|
+
let result;
|
|
52
|
+
switch (parsed.command) {
|
|
53
|
+
case "capabilities":
|
|
54
|
+
result = capabilitiesResult();
|
|
55
|
+
break;
|
|
56
|
+
case "terminal id":
|
|
57
|
+
if (parsed.harness === undefined)
|
|
58
|
+
throw new UsageError("terminal id requires --harness <name>");
|
|
59
|
+
result = { terminal_id: resolveHarnessTerminalId(parsed.harness) };
|
|
60
|
+
break;
|
|
61
|
+
case "payment-id":
|
|
62
|
+
result = paymentIdResult(readInput(parsed.input, stdin));
|
|
63
|
+
break;
|
|
64
|
+
case "key jkt":
|
|
65
|
+
result = keyJktResult(readInput(parsed.input, stdin));
|
|
66
|
+
break;
|
|
67
|
+
case "voucher sign":
|
|
68
|
+
if (parsed.envelope) {
|
|
69
|
+
result = voucherSignEnvelopeResult(readInput(parsed.input, stdin), terminalKey ?? parsed.key, stdin);
|
|
70
|
+
if (parsed.writeHeader !== undefined) {
|
|
71
|
+
const headerName = result.header_name;
|
|
72
|
+
const headerValue = result.header_value;
|
|
73
|
+
if (typeof headerName !== "string" || typeof headerValue !== "string") {
|
|
74
|
+
throw new SignerError("MALFORMED_ENVELOPE", "internal: header fields missing");
|
|
75
|
+
}
|
|
76
|
+
// Write a curl-ready header line ("<name>: <value>\n") BEFORE stdout, so the
|
|
77
|
+
// value can be replayed with `curl -H @<file>` without ever entering a shell
|
|
78
|
+
// argument or the model's context, and a failed write leaves no mismatched stdout.
|
|
79
|
+
try {
|
|
80
|
+
// mode 0600: the header line is a replayable credential until expiry.
|
|
81
|
+
writeFileSync(parsed.writeHeader, `${headerName}: ${headerValue}\n`, {
|
|
82
|
+
encoding: "utf8",
|
|
83
|
+
mode: 0o600,
|
|
84
|
+
});
|
|
85
|
+
// writeFileSync's `mode` is honored only when it creates the file; a
|
|
86
|
+
// pre-existing path keeps its old (possibly world-readable) perms, so
|
|
87
|
+
// tighten unconditionally — the line is a replayable credential.
|
|
88
|
+
chmodSync(parsed.writeHeader, 0o600);
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
throw new SignerError("MALFORMED_ENVELOPE", `cannot write header file: ${parsed.writeHeader}`);
|
|
92
|
+
}
|
|
93
|
+
// INV-1: the file is now the ONLY carrier of the credential. Drop header_value
|
|
94
|
+
// and its decomposed forms (the completed envelope and its signature) from the
|
|
95
|
+
// result so none reach stdout; report the file path plus non-secret metadata.
|
|
96
|
+
const { header_value: _hv, envelope: _env, signature: _sig, ...publicFields } = result;
|
|
97
|
+
result = { ...publicFields, header_file: parsed.writeHeader };
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
result = voucherSignResult(readInput(parsed.input, stdin), terminalKey ?? parsed.key, stdin);
|
|
102
|
+
}
|
|
103
|
+
break;
|
|
104
|
+
case "key generate": {
|
|
105
|
+
const input = readInput(parsed.input, stdin);
|
|
106
|
+
assertInputSchema("key generate", input);
|
|
107
|
+
let out = parsed.out;
|
|
108
|
+
if (parsed.terminal !== undefined) {
|
|
109
|
+
// The key file is named by --terminal, so the key inside must be bound to it too.
|
|
110
|
+
if (input.terminal_id !== parsed.terminal) {
|
|
111
|
+
throw new SignerError("TERMINAL_MISMATCH", "input terminal_id does not match --terminal");
|
|
112
|
+
}
|
|
113
|
+
out = terminalKeyPath(parsed.terminal, "ensure");
|
|
114
|
+
}
|
|
115
|
+
result = keyGenerateResult(input, out);
|
|
116
|
+
assertOutputSchema("key generate", result);
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
case "pop sign": {
|
|
120
|
+
const input = readInput(parsed.input, stdin);
|
|
121
|
+
assertInputSchema("pop sign", input);
|
|
122
|
+
result = popSignResult(input, terminalKey ?? parsed.key, stdin);
|
|
123
|
+
assertOutputSchema("pop sign", result);
|
|
124
|
+
break;
|
|
125
|
+
}
|
|
126
|
+
case "verify-vectors": {
|
|
127
|
+
const { result: summary, ok } = verifyVectorsResult();
|
|
128
|
+
return { stdout: format(summary, parsed.output), stderr: "", exitCode: ok ? 0 : 1 };
|
|
129
|
+
}
|
|
130
|
+
default:
|
|
131
|
+
// Later tasks add the signing/read commands here.
|
|
132
|
+
throw new UsageError(`command not implemented: ${parsed.command}`);
|
|
133
|
+
}
|
|
134
|
+
return { stdout: format(result, parsed.output), stderr: "", exitCode: 0 };
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
if (error instanceof UsageError) {
|
|
138
|
+
return { stdout: "", stderr: `${error.message}\n`, exitCode: 2 };
|
|
139
|
+
}
|
|
140
|
+
const code = error instanceof SignerError ? error.code : "MALFORMED_ENVELOPE";
|
|
141
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
142
|
+
return {
|
|
143
|
+
stdout: "",
|
|
144
|
+
stderr: `${JSON.stringify({ error: { code, message } })}\n`,
|
|
145
|
+
exitCode: 1,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
}
|