everything-dev
Version:
A consolidated product package for building Module Federation apps with oRPC APIs.
76 lines (74 loc) • 2.83 kB
JavaScript
import { authPost } from "./site-client.mjs";
import { openInBrowser, startDeviceLogin } from "./device-login.mjs";
import { generateNearKeyPair } from "./near-cli.mjs";
import { readSessionHandle, updateSessionHandle } from "./session.mjs";
import { Near, isPrivateKey } from "near-kit";
//#region src/services/auth/delegate-signer.ts
const realSiteClient = { authPost };
function relayErrorMessage(message) {
return message.replace(/\n/g, " ");
}
async function submitRegistryWriteDelegated(opts, siteClient = realSiteClient) {
const delegate = await new Near({
network: opts.network,
defaultSignerId: opts.account,
privateKey: assertPrivateKey(opts.delegatePrivateKey)
}).transaction(opts.account).functionCall(opts.contract, "__fastdata_kv", opts.args, {
gas: "300 Tgas",
attachedDeposit: "0 yocto"
}).delegate({
receiverId: opts.contract,
blockHeightOffset: 200
});
const { status, json } = await siteClient.authPost(opts.relayEndpoint.replace(/\/api\/auth\/near\/relay$/, ""), "/near/relay", { payload: delegate.payload }, void 0, { "x-api-key": opts.apiKey });
if (status >= 400) {
let detail = `Relay rejected the transaction (HTTP ${status})`;
const relayMessage = typeof json.message === "string" ? json.message : typeof json.error === "string" ? json.error : void 0;
if (relayMessage) detail = `${detail}: ${relayErrorMessage(relayMessage)}`;
throw new Error(detail);
}
return {
success: true,
txHash: json.txHash
};
}
function assertPrivateKey(key) {
if (!isPrivateKey(key)) throw new Error("Invalid delegate key format (expected ed25519:…)");
return key;
}
async function ensureDelegateKey(opts) {
const existing = readSessionHandle(opts.configDir)?.delegateKey;
if (existing && existing.accountId === opts.account && existing.contract === opts.contract && existing.network === opts.network) return existing;
const keyPair = generateNearKeyPair();
const login = await startDeviceLogin({
siteUrl: opts.siteUrl,
delegate: {
pubKey: keyPair.publicKey,
contract: opts.contract,
network: opts.network
},
account: opts.account
});
console.log(` One-time code: ${login.userCode}`);
await openInBrowser(login.verificationUrl).catch((error) => {
console.log(` ⚠ ${error.message}`);
});
console.log(` Waiting for delegate-key approval at ${login.verificationUrl}…`);
await login.waitForApproval();
const record = {
publicKey: keyPair.publicKey,
privateKey: keyPair.privateKey,
accountId: opts.account,
network: opts.network,
contract: opts.contract,
mintedAt: (/* @__PURE__ */ new Date()).toISOString()
};
updateSessionHandle(opts.configDir, (current) => ({
...current,
delegateKey: record
}));
return record;
}
//#endregion
export { ensureDelegateKey, submitRegistryWriteDelegated };
//# sourceMappingURL=delegate-signer.mjs.map