@swarm-tips/client 0.2.13 → 0.3.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.
@@ -0,0 +1,175 @@
1
+ import { Buffer } from "buffer";
2
+ import bs58 from "bs58";
3
+ import { SwarmClientError } from "../errors.js";
4
+ import { HttpClient } from "../http.js";
5
+ function parseJwtClaims(token) {
6
+ const parts = token.split(".");
7
+ if (parts.length < 2)
8
+ return {};
9
+ try {
10
+ const b64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
11
+ const padded = b64 + "=".repeat((4 - (b64.length % 4)) % 4);
12
+ const parsed = JSON.parse(Buffer.from(padded, "base64").toString("utf8"));
13
+ return parsed && typeof parsed === "object" ? parsed : {};
14
+ }
15
+ catch {
16
+ return {};
17
+ }
18
+ }
19
+ const DEFAULT_OPAQUE_TTL_MS = 23 * 60 * 60 * 1_000;
20
+ /**
21
+ * Non-custodial JWT manager backed by `game-api` wallet challenges:
22
+ * - Solana: `POST /auth/challenge` + `POST /auth/verify` (Ed25519 detached bs58)
23
+ * - EVM: `POST /auth/evm/challenge` + `POST /auth/evm/verify` (EIP-191 personal_sign)
24
+ *
25
+ * Caches minted tokens until `(exp - 60) * 1000`, deduplicates concurrent refresh
26
+ * calls, and exposes `invalidate()` for single-retry 401 recovery.
27
+ */
28
+ export class WalletTokenManager {
29
+ signer;
30
+ staticToken;
31
+ customGetToken;
32
+ http;
33
+ now;
34
+ cachedToken = null;
35
+ expiresAtMs = 0;
36
+ inFlight = null;
37
+ constructor(options = {}) {
38
+ this.signer = options.signer;
39
+ if (typeof options.token === "string") {
40
+ this.staticToken = options.token;
41
+ }
42
+ else if (typeof options.token === "function") {
43
+ this.customGetToken = options.token;
44
+ }
45
+ this.http = new HttpClient({
46
+ baseUrl: options.gameUrl ?? "https://api.coordination.game",
47
+ fetch: options.fetch,
48
+ });
49
+ this.now = options.now ?? (() => Date.now());
50
+ }
51
+ get walletAddress() {
52
+ if (this.signer)
53
+ return this.signer.address;
54
+ const candidate = this.staticToken ?? this.cachedToken;
55
+ if (!candidate)
56
+ return undefined;
57
+ const claims = parseJwtClaims(candidate);
58
+ return claims.wallet ?? claims.sub;
59
+ }
60
+ invalidate() {
61
+ this.cachedToken = null;
62
+ this.expiresAtMs = 0;
63
+ }
64
+ async getToken() {
65
+ if (this.staticToken !== undefined) {
66
+ return this.staticToken;
67
+ }
68
+ if (this.customGetToken) {
69
+ return this.customGetToken();
70
+ }
71
+ if (!this.signer) {
72
+ return undefined;
73
+ }
74
+ if (this.cachedToken && this.now() < this.expiresAtMs) {
75
+ return this.cachedToken;
76
+ }
77
+ return this.authenticate();
78
+ }
79
+ async authenticate() {
80
+ if (this.staticToken !== undefined) {
81
+ return this.staticToken;
82
+ }
83
+ if (this.customGetToken) {
84
+ const resolved = await this.customGetToken();
85
+ if (!resolved) {
86
+ throw new SwarmClientError({
87
+ code: "AUTH_REQUIRED",
88
+ operation: "auth.authenticate",
89
+ message: "Token callback returned no token",
90
+ });
91
+ }
92
+ return resolved;
93
+ }
94
+ if (!this.signer) {
95
+ throw new SwarmClientError({
96
+ code: "AUTH_REQUIRED",
97
+ operation: "auth.authenticate",
98
+ message: "A SwarmSigner or token is required to authenticate",
99
+ });
100
+ }
101
+ if (this.inFlight) {
102
+ return this.inFlight;
103
+ }
104
+ const signer = this.signer;
105
+ this.inFlight = (async () => {
106
+ try {
107
+ let token;
108
+ if (signer.chain === "solana") {
109
+ const challenge = await this.http.post("/auth/challenge", {
110
+ wallet: signer.address,
111
+ });
112
+ if (!challenge?.nonce) {
113
+ throw new SwarmClientError({
114
+ code: "INVALID_RESPONSE",
115
+ operation: "auth.challenge",
116
+ message: "Auth challenge returned no nonce",
117
+ });
118
+ }
119
+ const sigBytes = await signer.signMessage(new TextEncoder().encode(challenge.nonce));
120
+ const verified = await this.http.post("/auth/verify", {
121
+ wallet: signer.address,
122
+ nonce: challenge.nonce,
123
+ signature: bs58.encode(sigBytes),
124
+ });
125
+ if (!verified?.token) {
126
+ throw new SwarmClientError({
127
+ code: "INVALID_RESPONSE",
128
+ operation: "auth.verify",
129
+ message: "Auth verify returned no token",
130
+ });
131
+ }
132
+ token = verified.token;
133
+ }
134
+ else {
135
+ const challenge = await this.http.post("/auth/evm/challenge", {
136
+ wallet: signer.address,
137
+ });
138
+ if (!challenge?.nonce) {
139
+ throw new SwarmClientError({
140
+ code: "INVALID_RESPONSE",
141
+ operation: "auth.evmChallenge",
142
+ message: "EVM auth challenge returned no nonce",
143
+ });
144
+ }
145
+ const signature = await signer.signMessage(challenge.nonce);
146
+ const verified = await this.http.post("/auth/evm/verify", {
147
+ wallet: signer.address,
148
+ nonce: challenge.nonce,
149
+ signature,
150
+ });
151
+ if (!verified?.token) {
152
+ throw new SwarmClientError({
153
+ code: "INVALID_RESPONSE",
154
+ operation: "auth.evmVerify",
155
+ message: "EVM auth verify returned no token",
156
+ });
157
+ }
158
+ token = verified.token;
159
+ }
160
+ const claims = parseJwtClaims(token);
161
+ const nowMs = this.now();
162
+ this.cachedToken = token;
163
+ this.expiresAtMs =
164
+ typeof claims.exp === "number"
165
+ ? (claims.exp - 60) * 1_000
166
+ : nowMs + DEFAULT_OPAQUE_TTL_MS;
167
+ return token;
168
+ }
169
+ finally {
170
+ this.inFlight = null;
171
+ }
172
+ })();
173
+ return this.inFlight;
174
+ }
175
+ }
@@ -0,0 +1,24 @@
1
+ import type { SwarmSigner } from "../signer/types.js";
2
+ export declare class CliUsageError extends Error {
3
+ readonly exitCode = 2;
4
+ constructor(message: string);
5
+ }
6
+ /**
7
+ * C6 CLI security invariant: reject raw secret material passed on argv
8
+ * (visible to `ps` and shell history) without ever echoing the secret value.
9
+ */
10
+ export declare function assertNoSecretCliFlags(argv: readonly string[]): void;
11
+ /**
12
+ * Verify keyfile exists and is owner-only (`0o600` / `0o400`) on POSIX before reading.
13
+ */
14
+ export declare function readSecureKeypairFile(filePath: string): string;
15
+ export interface LoadCliSignerOptions {
16
+ keypairFile?: string;
17
+ env?: Record<string, string | undefined>;
18
+ evmChainId?: number;
19
+ evmRpcUrl?: string;
20
+ }
21
+ /**
22
+ * Load a non-custodial `SwarmSigner` from `--keypair-file` or `SWARM_*` environment variables.
23
+ */
24
+ export declare function loadSignerFromCliOrEnv(options?: LoadCliSignerOptions): SwarmSigner | undefined;
@@ -0,0 +1,97 @@
1
+ import { readFileSync, statSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { fromEvmPrivateKey } from "../signer/evm.js";
4
+ import { fromSolanaSecretKey } from "../signer/solana.js";
5
+ export class CliUsageError extends Error {
6
+ exitCode = 2;
7
+ constructor(message) {
8
+ super(message);
9
+ this.name = "CliUsageError";
10
+ }
11
+ }
12
+ const FORBIDDEN_SECRET_FLAGS = [
13
+ "--private-key",
14
+ "--secret-key",
15
+ "--mnemonic",
16
+ "--seed",
17
+ ];
18
+ /**
19
+ * C6 CLI security invariant: reject raw secret material passed on argv
20
+ * (visible to `ps` and shell history) without ever echoing the secret value.
21
+ */
22
+ export function assertNoSecretCliFlags(argv) {
23
+ for (const arg of argv) {
24
+ const lower = arg.toLowerCase();
25
+ for (const forbidden of FORBIDDEN_SECRET_FLAGS) {
26
+ if (lower === forbidden || lower.startsWith(`${forbidden}=`)) {
27
+ throw new CliUsageError(`Refusing ${forbidden} on the command line (argv is visible in process listings and shell history). ` +
28
+ `Pass --keypair-file <path> (chmod 600) or set SWARM_SOLANA_KEYPAIR_PATH, SWARM_SOLANA_SECRET_KEY, or SWARM_EVM_PRIVATE_KEY.`);
29
+ }
30
+ }
31
+ }
32
+ }
33
+ /**
34
+ * Verify keyfile exists and is owner-only (`0o600` / `0o400`) on POSIX before reading.
35
+ */
36
+ export function readSecureKeypairFile(filePath) {
37
+ const resolved = resolve(filePath);
38
+ let stat;
39
+ try {
40
+ stat = statSync(resolved);
41
+ }
42
+ catch (err) {
43
+ throw new CliUsageError(`Cannot access keypair file ${resolved}: ${err instanceof Error ? err.message : String(err)}`);
44
+ }
45
+ if (!stat.isFile()) {
46
+ throw new CliUsageError(`Keypair path ${resolved} is not a regular file.`);
47
+ }
48
+ if (process.platform !== "win32" && (stat.mode & 0o077) !== 0) {
49
+ const modeOctal = (stat.mode & 0o777).toString(8).padStart(3, "0");
50
+ throw new CliUsageError(`Refusing keypair file ${resolved} with insecure permissions 0${modeOctal} (group/world accessible). Run: chmod 600 ${resolved}`);
51
+ }
52
+ try {
53
+ return readFileSync(resolved, "utf8").trim();
54
+ }
55
+ catch (err) {
56
+ throw new CliUsageError(`Failed to read keypair file ${resolved}: ${err instanceof Error ? err.message : String(err)}`);
57
+ }
58
+ }
59
+ /**
60
+ * Load a non-custodial `SwarmSigner` from `--keypair-file` or `SWARM_*` environment variables.
61
+ */
62
+ export function loadSignerFromCliOrEnv(options = {}) {
63
+ const env = options.env ?? process.env;
64
+ const keyfilePath = options.keypairFile ?? env.SWARM_SOLANA_KEYPAIR_PATH;
65
+ if (keyfilePath) {
66
+ const raw = readSecureKeypairFile(keyfilePath);
67
+ try {
68
+ return fromSolanaSecretKey(raw);
69
+ }
70
+ catch (err) {
71
+ throw new CliUsageError(`Invalid Solana keypair in ${resolve(keyfilePath)}: ${err instanceof Error ? err.message : String(err)}`);
72
+ }
73
+ }
74
+ const solSecret = env.SWARM_SOLANA_SECRET_KEY?.trim();
75
+ if (solSecret) {
76
+ try {
77
+ return fromSolanaSecretKey(solSecret);
78
+ }
79
+ catch (err) {
80
+ throw new CliUsageError(`Invalid SWARM_SOLANA_SECRET_KEY: ${err instanceof Error ? err.message : String(err)}`);
81
+ }
82
+ }
83
+ const evmPriv = env.SWARM_EVM_PRIVATE_KEY?.trim();
84
+ if (evmPriv) {
85
+ const normalized = (evmPriv.startsWith("0x") ? evmPriv : `0x${evmPriv}`);
86
+ try {
87
+ return fromEvmPrivateKey(normalized, {
88
+ chainId: options.evmChainId,
89
+ rpcUrl: options.evmRpcUrl,
90
+ });
91
+ }
92
+ catch (err) {
93
+ throw new CliUsageError(`Invalid SWARM_EVM_PRIVATE_KEY: ${err instanceof Error ? err.message : String(err)}`);
94
+ }
95
+ }
96
+ return undefined;
97
+ }
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ export interface CliIo {
3
+ stdout?: {
4
+ write: (chunk: string) => boolean;
5
+ isTTY?: boolean;
6
+ };
7
+ stderr?: {
8
+ write: (chunk: string) => boolean;
9
+ };
10
+ stdin?: () => string | Promise<string>;
11
+ env?: Record<string, string | undefined>;
12
+ fetch?: typeof fetch;
13
+ }
14
+ export declare function runSwarmCli(argv: readonly string[], io?: CliIo): Promise<number>;