2026-01-13 14:49:19 +01:00

54 lines
1.4 KiB
TypeScript

import { nip19 } from 'nostr-tools'
export function extractKeyFromInput(rawInput: string): string | null {
const trimmed = rawInput.trim()
if (trimmed.length === 0) {
return null
}
const fromUrl = extractKeyFromUrl(trimmed)
return fromUrl ?? extractKeyFromText(trimmed)
}
function extractKeyFromUrl(url: string): string | null {
try {
const urlObj = new URL(url)
const {protocol} = urlObj
if (protocol === 'nostr:' || protocol === 'nostr://') {
const path = urlObj.pathname ?? urlObj.href.replace(/^nostr:?\/\//, '')
if (path.startsWith('nsec')) {
return path
}
}
const nsecMatch = url.match(/nsec1[a-z0-9]+/i)
return nsecMatch?.[0] ?? null
} catch {
return null
}
}
function extractKeyFromText(text: string): string | null {
const nsec = extractNsec(text)
if (nsec) {
return nsec
}
const trimmed = text.trim()
return trimmed.length > 0 ? trimmed : null
}
function extractNsec(text: string): string | null {
const nsecMatch = text.match(/nsec1[a-z0-9]+/i)
return nsecMatch?.[0] ?? null
}
export function isValidPrivateKeyFormat(key: string): boolean {
try {
const decoded = nip19.decode(key)
if (decoded.type !== 'nsec') {
return false
}
return typeof decoded.data === 'string' || decoded.data instanceof Uint8Array
} catch {
return /^[0-9a-f]{64}$/i.test(key)
}
}