-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathindex.ts
More file actions
286 lines (257 loc) · 9.54 KB
/
Copy pathindex.ts
File metadata and controls
286 lines (257 loc) · 9.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/**
* Synapse SDK initialization for filecoin-pin
*
* Maps CLI-friendly configuration (private key strings, RPC URLs) to the
* SDK's viem-based options (Accounts, Transports, Chains). Consumers use
* the returned Synapse instance directly for storage operations.
*
* @module core/synapse
*/
import { type Chain, calibration, mainnet, Synapse, type SynapseOptions } from '@filoz/synapse-sdk'
export { calibration, mainnet, type Chain }
import type { SessionKey } from '@filoz/synapse-core/session-key'
import {
AddPiecesPermission,
CreateDataSetPermission,
DefaultFwssPermissions,
fromSecp256k1,
SchedulePieceRemovalsPermission,
TerminateServicePermission,
} from '@filoz/synapse-core/session-key'
import type { Logger } from 'pino'
import {
type Account,
type Address,
custom,
getAddress,
type Hex,
type HttpTransport,
type WebSocketTransport,
} from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { APPLICATION_SOURCE } from './constants.js'
import { createTransport } from './create-transport.js'
import { resolveChainFromRpc } from './resolve-chain-from-rpc.js'
export * from './constants.js'
export { createTransport } from './create-transport.js'
/**
* Application configuration for CLI and pinning server
*/
export interface Config {
port: number
host: string
privateKey: string | undefined
walletAddress: string | undefined
sessionKey: string | undefined
accessToken: string | undefined
/** Allow the pinning server to start without an access token, serving all requests unauthenticated. */
allowNoAuth?: boolean
rpcUrl: string
chain?: Chain
databasePath: string
carStoragePath: string
logLevel: string
}
/**
* Common options for all Synapse configurations
*/
interface BaseSynapseConfig {
/** RPC endpoint for the target Filecoin network. Defaults to mainnet chain transport. */
rpcUrl?: string
/** Target chain. Defaults to mainnet. */
chain?: Chain
/** Enable CDN service for datasets */
withCDN?: boolean
/** Default metadata to apply when creating datasets */
dataSetMetadata?: Record<string, string>
}
/**
* Standard authentication with private key
*/
export interface PrivateKeyConfig extends BaseSynapseConfig {
privateKey: Hex
}
/**
* Session key authentication with owner address and session key private key
*/
export interface SessionKeyConfig extends BaseSynapseConfig {
walletAddress: Address
sessionKey: Hex
}
/**
* Read-only mode using an address (cannot sign transactions)
*/
export interface ReadOnlyConfig extends BaseSynapseConfig {
walletAddress: Address
readOnly: true
}
/**
* Pre-created viem Account
*/
export interface AccountConfig extends BaseSynapseConfig {
account: Account
}
/**
* Configuration for Synapse initialization.
*
* Supports four authentication modes:
* 1. Private key: hex-encoded private key string
* 2. Session key: owner wallet address + session key private key
* 3. Read-only: wallet address for querying without signing
* 4. Account: pre-created viem Account instance
*/
export type SynapseSetupConfig = PrivateKeyConfig | SessionKeyConfig | ReadOnlyConfig | AccountConfig
function isPrivateKeyConfig(config: SynapseSetupConfig): config is PrivateKeyConfig {
return 'privateKey' in config && config.privateKey != null
}
function isSessionKeyConfig(config: SynapseSetupConfig): config is SessionKeyConfig {
return (
'walletAddress' in config &&
'sessionKey' in config &&
config.walletAddress != null &&
(config as SessionKeyConfig).sessionKey != null &&
!('readOnly' in config && (config as ReadOnlyConfig).readOnly === true)
)
}
function isReadOnlyConfig(config: SynapseSetupConfig): config is ReadOnlyConfig {
return 'readOnly' in config && (config as ReadOnlyConfig).readOnly === true && 'walletAddress' in config
}
const PERMISSION_NAMES: Record<string, string> = {
[CreateDataSetPermission]: 'CreateDataSet',
[TerminateServicePermission]: 'TerminateService',
[AddPiecesPermission]: 'AddPieces',
[SchedulePieceRemovalsPermission]: 'SchedulePieceRemovals',
}
function checkSessionKeyPermissions(key: SessionKey<'Secp256k1'>, ownerAddress: string): void {
const missing = DefaultFwssPermissions.filter((p) => !key.hasPermission(p))
if (missing.length === 0) return
const now = BigInt(Math.floor(Date.now() / 1000))
const lines = missing.map((p) => {
const name = PERMISSION_NAMES[p] ?? p
const expiry = key.expirations[p] ?? 0n
if (expiry > 0n && expiry < now) {
return ` • ${name}: expired at ${new Date(Number(expiry) * 1000).toISOString()}`
}
return ` • ${name}: never authorized`
})
const footnotes = missing.map((p) => ` ${PERMISSION_NAMES[p] ?? p}: ${p}`)
throw new Error(
`Session key ${key.address} is missing ${missing.length} required permission(s):\n` +
lines.join('\n') +
`\nAuthorize this session key from owner wallet ${ownerAddress}.\nPermission hashes:\n` +
footnotes.join('\n')
)
}
/**
* Create a Synapse instance from CLI-friendly configuration.
*
* @param config - Authentication and network configuration
* @param logger - Optional logger for initialization events
* @returns Initialized Synapse instance
*/
export async function initializeSynapse(config: SynapseSetupConfig, logger?: Logger): Promise<Synapse> {
let chain: Chain
let rpcUrl: string | undefined
let transport: HttpTransport | WebSocketTransport | undefined
if (config.rpcUrl) {
// Probe the RPC endpoint's chainId so the chain object reflects what the endpoint actually serves.
// CLI/server callers enforce that --rpc-url is mutually exclusive with --network, so any chain hint
// here is from a programmatic caller and is treated as advisory.
rpcUrl = config.rpcUrl
transport = createTransport(rpcUrl)
chain = await resolveChainFromRpc(transport, logger)
} else {
chain = config.chain ?? mainnet
rpcUrl = chain.rpcUrls.default.webSocket?.[0] ?? chain.rpcUrls.default.http[0]
transport = rpcUrl ? createTransport(rpcUrl) : undefined
}
let account: Account | Address
let sessionKey: SessionKey<'Secp256k1'> | undefined
if (isReadOnlyConfig(config)) {
account = getAddress(config.walletAddress)
logger?.info({ event: 'synapse.init', mode: 'read-only' }, 'Initializing Synapse (read-only)')
} else if (isSessionKeyConfig(config)) {
const walletAddress = getAddress(config.walletAddress)
account = walletAddress
sessionKey = fromSecp256k1({
privateKey: config.sessionKey,
root: walletAddress,
chain,
...(transport ? { transport } : {}),
})
await sessionKey.syncExpirations()
checkSessionKeyPermissions(sessionKey, walletAddress)
logger?.info({ event: 'synapse.init', mode: 'session-key' }, 'Initializing Synapse (session key)')
} else if (isPrivateKeyConfig(config)) {
account = privateKeyToAccount(config.privateKey)
logger?.info({ event: 'synapse.init', mode: 'private-key' }, 'Initializing Synapse')
} else if ('account' in config && config.account != null) {
account = config.account
logger?.info({ event: 'synapse.init', mode: 'account' }, 'Initializing Synapse (pre-created account)')
} else {
const hasWallet = 'walletAddress' in config && config.walletAddress != null
const hasSessionKey = 'sessionKey' in config && config.sessionKey != null
if (hasWallet && !hasSessionKey) {
throw new Error(
'Session key authentication requires both --wallet-address and --session-key. ' +
'Missing: --session-key / SESSION_KEY.'
)
}
if (hasSessionKey && !hasWallet) {
throw new Error(
'Session key authentication requires both --wallet-address and --session-key. ' +
'Missing: --wallet-address / WALLET_ADDRESS.'
)
}
throw new Error(
'No authentication provided. Supply an OWS wallet (--wallet / OWS_WALLET_ID), ' +
'private key (--private-key / PRIVATE_KEY), ' +
'wallet address (--wallet-address / WALLET_ADDRESS), or session key (--session-key / SESSION_KEY).'
)
}
const synapseOptions: SynapseOptions = {
account,
chain,
source: APPLICATION_SOURCE,
}
if (transport) {
// Synapse SDK rejects non-custom transports for json-rpc accounts (where
// account is a bare address string rather than a full Account object).
// Both read-only and session key modes use bare addresses, so wrap in
// custom() to satisfy the guard while preserving the underlying transport.
if (typeof account === 'string') {
const resolved = transport({ chain, retryCount: 0 })
synapseOptions.transport = custom({ request: resolved.request })
} else {
synapseOptions.transport = transport
}
}
if (sessionKey) {
synapseOptions.sessionKey = sessionKey
}
if (config.withCDN) {
synapseOptions.withCDN = config.withCDN
}
const synapse = Synapse.create(synapseOptions)
logger?.info({ event: 'synapse.init.success', chain: synapse.chain.name }, 'Synapse initialized')
return synapse
}
/**
* Extract the client wallet address from a Synapse instance.
*
* Handles both string addresses (read-only / session key mode) and
* full Account objects (private key mode).
*/
export function getClientAddress(synapse: Synapse): Address {
const account = synapse.client.account
return (typeof account === 'string' ? account : account.address) as Address
}
/**
* Check if Synapse is using session key authentication.
*
* Session key mode restricts transaction signing to scoped operations;
* payment setup must be done by the owner wallet separately.
*/
export function isSessionKeyMode(synapse: Synapse): boolean {
return synapse.sessionClient != null
}