Repository navigation
Expand file tree
/
Copy pathfederation.js
More file actions
253 lines (229 loc) · 9.58 KB
/
Copy pathfederation.js
File metadata and controls
253 lines (229 loc) · 9.58 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
import * as StellarSDK from '@stellar/stellar-sdk';
import prisma from '../db/client.js';
import { getConfig } from '../config/env.js';
import { RedisBackend } from '../cache/redis.js';
import { createCircuitBreaker } from './circuitBreaker.js';
const DEFAULT_FEDERATION_DOMAIN = 'futureremit.app';
const FEDERATION_TOML_TTL_SECONDS = 24 * 60 * 60;
const FEDERATION_RESULT_TTL_SECONDS = 5 * 60;
const FEDERATION_NEGATIVE_TTL_SECONDS = 30;
const FEDERATION_TIMEOUT_MS = 10_000;
const federationEndpointCache = new Map();
const federationResultCache = new Map();
const federationBreakers = new Map();
const federationRedis = new RedisBackend();
function getFederationBreaker(domain) {
if (!federationBreakers.has(domain)) {
federationBreakers.set(domain, createCircuitBreaker(`Federation-${domain}`, {
failureThreshold: 3,
probeIntervalMs: 60_000,
}));
}
return federationBreakers.get(domain);
}
function parseTomlField(toml, field) {
const match = String(toml).match(new RegExp(`^\\s*${field}\\s*=\\s*["']([^"']+)["']`, 'mi'));
return match?.[1]?.trim() || null;
}
async function fetchWithTimeout(url) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FEDERATION_TIMEOUT_MS);
try {
const response = await fetch(url, { signal: controller.signal, headers: { accept: 'application/json,text/plain' } });
if (!response.ok) throw new Error(`Federation upstream returned ${response.status}`);
return response;
} finally {
clearTimeout(timer);
}
}
async function getCached(key, localCache) {
const local = localCache.get(key);
if (local && local.expiresAt > Date.now()) return local.value;
if (local) localCache.delete(key);
const remote = await federationRedis.get(key);
if (remote?.value && remote.expiresAt > Date.now()) {
localCache.set(key, remote);
return remote.value;
}
return null;
}
async function setCached(key, value, ttlSeconds, localCache) {
const record = { value, expiresAt: Date.now() + ttlSeconds * 1000 };
localCache.set(key, record);
await federationRedis.set(key, record, ttlSeconds);
}
/**
* Get the domain this platform serves federation lookups for.
* @returns {string} The federation domain, from STELLAR_FEDERATION_DOMAIN or the built-in default
*/
export function getFederationDomain() {
return process.env.STELLAR_FEDERATION_DOMAIN || DEFAULT_FEDERATION_DOMAIN;
}
/**
* Normalize a federation address for comparison/storage (trim + lowercase).
* @param {string} address - Raw federation address, e.g. "Alice*Example.com"
* @returns {string} Normalized address, e.g. "alice*example.com"
*/
export function normalizeFederationAddress(address) {
return String(address || '').trim().toLowerCase();
}
/**
* Check whether a string has the shape of a federation address (`local*domain.tld`).
* @param {string} address - Address to test
* @returns {boolean} True if the address matches the federation address pattern
*/
export function isFederationAddress(address) {
return /^[a-z0-9._-]+\*[a-z0-9.-]+\.[a-z]{2,}$/i.test(String(address || '').trim());
}
/**
* Resolve a federation address to its Stellar account id, per SEP-0002.
* @param {string} address - Federation address to resolve, e.g. "alice*futureremit.app"
* @returns {Promise<{stellar_address: string, account_id: string, memo_type: string}>} SEP-0002 federation response
* @throws {Error} With `status` 400 if the address is malformed, or 404 if the domain isn't served here or no matching account exists
*/
export async function resolveFederationAddress(address) {
const normalized = normalizeFederationAddress(address);
if (!isFederationAddress(normalized)) {
const error = new Error('Invalid federation address');
error.status = 400;
throw error;
}
const [, domain] = normalized.split('*');
if (domain !== getFederationDomain().toLowerCase()) {
const resultKey = `federation:result:${normalized}`;
const cachedResult = await getCached(resultKey, federationResultCache);
if (cachedResult) {
if (cachedResult.notFound) {
const error = new Error('Federation address not found');
error.status = 404;
throw error;
}
return cachedResult;
}
try {
const breaker = getFederationBreaker(domain);
const endpointKey = `federation:endpoint:${domain}`;
let federationServer = await getCached(endpointKey, federationEndpointCache);
if (!federationServer) {
federationServer = await breaker.call(async () => {
const tomlResponse = await fetchWithTimeout(`https://${domain}/.well-known/stellar.toml`);
const endpoint = parseTomlField(await tomlResponse.text(), 'FEDERATION_SERVER');
if (!endpoint) throw new Error(`No FEDERATION_SERVER advertised by ${domain}`);
return endpoint;
});
await setCached(endpointKey, federationServer, FEDERATION_TOML_TTL_SECONDS, federationEndpointCache);
}
const url = new URL(federationServer);
url.searchParams.set('q', normalized.split('*')[0]);
url.searchParams.set('type', 'name');
const response = await breaker.call(() => fetchWithTimeout(url.toString()));
const result = await response.json();
if (!result?.account_id) {
await setCached(resultKey, { notFound: true }, FEDERATION_NEGATIVE_TTL_SECONDS, federationResultCache);
const error = new Error('Federation address not found');
error.status = 404;
throw error;
}
const resolved = {
stellar_address: result.stellar_address || normalized,
account_id: result.account_id,
memo_type: result.memo_type || 'none',
...(result.memo ? { memo: result.memo } : {}),
};
await setCached(resultKey, resolved, FEDERATION_RESULT_TTL_SECONDS, federationResultCache);
return resolved;
} catch (error) {
if (error.status === 404) throw error;
throw Object.assign(new Error('Federation service unavailable'), { status: 503, cause: error });
}
}
const setting = await prisma.setting.findFirst({
where: { federationAddress: normalized },
include: { user: { select: { publicKey: true } } },
});
if (!setting?.user?.publicKey) {
const error = new Error('Federation address not found');
error.status = 404;
throw error;
}
return {
stellar_address: normalized,
account_id: setting.user.publicKey,
memo_type: 'none',
};
}
/**
* Claim a federation address (local part) for a user's Stellar account, creating the
* user/settings record if it doesn't already exist.
* @param {object} opts
* @param {string} opts.publicKey - Stellar public key to associate with the federation address
* @param {string} opts.localPart - Desired local part (before the `*`), 3-32 chars: letters, numbers, `.`, `_`, `-`
* @returns {Promise<{federationAddress: string}>} The claimed, fully-qualified federation address
* @throws {Error} With `status` 400 if localPart doesn't meet the format requirements
*/
export async function claimFederationAddress({ publicKey, localPart }) {
const safeLocalPart = String(localPart || '').trim().toLowerCase();
if (!/^[a-z0-9._-]{3,32}$/.test(safeLocalPart)) {
const error = new Error('Federation name must be 3-32 characters: letters, numbers, dot, underscore, or hyphen');
error.status = 400;
throw error;
}
const federationAddress = `${safeLocalPart}*${getFederationDomain().toLowerCase()}`;
const user = await prisma.user.upsert({
where: { publicKey },
update: {},
create: { publicKey },
});
const setting = await prisma.setting.upsert({
where: { userId: user.id },
update: { federationAddress },
create: { userId: user.id, federationAddress },
});
return { federationAddress: setting.federationAddress };
}
/**
* ACCOUNTS in a SEP-1 stellar.toml is meant to list this platform's known
* Stellar accounts for wallet discovery. The only account the platform
* controls end-to-end today is the fee-sponsoring account used for fee-bump
* transactions (see wrapWithFeeBump in services/stellar.js) — if that isn't
* configured, there is intentionally nothing else to list here yet.
* See issue #954.
* @returns {string[]} Public keys to advertise in ACCOUNTS.
*/
function getKnownAccounts() {
const feeSecret = process.env.PLATFORM_FEE_ACCOUNT_SECRET;
if (!feeSecret) return [];
try {
return [StellarSDK.Keypair.fromSecret(feeSecret).publicKey()];
} catch {
return [];
}
}
/**
* Build this platform's SEP-1 stellar.toml contents, sourced entirely
* through getConfig() rather than raw process.env. Shared by the canonical
* /.well-known/stellar.toml route (server.js) and the federation-scoped
* /api/v1/stellar/federation/stellar.toml route (routes/stellar/federation.js)
* so the two can't drift out of sync. See issue #954.
* @returns {string} The stellar.toml document body.
*/
export function buildStellarToml() {
const { stellar } = getConfig();
const baseUrl = stellar.serverBaseUrl;
const networkPassphrase =
stellar.network === 'mainnet'
? 'Public Global Stellar Network ; September 2015'
: 'Test SDF Network ; September 2015';
const accounts = getKnownAccounts();
return [
`FEDERATION_SERVER="${baseUrl}/api/v1/stellar/federation"`,
`SIGNING_KEY="${stellar.signingKey}"`,
`NETWORK_PASSPHRASE="${networkPassphrase}"`,
`TRANSFER_SERVER="${baseUrl}/api/v1/stellar"`,
// Advertises this platform as a SEP-0031 sending anchor. See issue #955.
`DIRECT_PAYMENT_SERVER="${baseUrl}/api/v1/stellar/sep31"`,
`ACCOUNTS=[${accounts.map((account) => `"${account}"`).join(', ')}]`,
`VERSION="2.0.0"`,
`# Federation domain: ${getFederationDomain()}`,
].join('\n');
}