0
0
import { BrowserOAuthClient } from '@atproto/oauth-client-browser';
import { Agent } from '@atproto/api';
import { XrpcClient } from '@atproto/xrpc';
import { toDataURL } from 'qrcode';
import jsQR from 'jsqr';
import { OAUTH_SCOPE_FULL } from './generated/oauth-scope.js';
export const BADGE_BLUE_KEYS_NSID = 'com.publicdomainrelay.temp.badgeBlueKeys';
const ASSOCIATE_CONFIRM_NSID = 'com.publicdomainrelay.temp.requester.associateConfirm';
const ASSOCIATE_LEXICON_STUBS = [
{ lexicon: 1, id: ASSOCIATE_CONFIRM_NSID, defs: { main: { type: 'procedure' } } },
];
/* ── Structured JSON logger ── */
export function log(level, component, event, data = {}) {
const line = JSON.stringify({ ts: new Date().toISOString(), level, component, event, ...data });
if (level === 'error' || level === 'warn') console.error(line);
else console.log(line);
}
/* ── OAuth client id ── */
export function buildClientID() {
const isLocal = ["localhost", "127.0.0.1"].includes(window.location.hostname);
if (isLocal) {
return `http://localhost?${new URLSearchParams({
scope: OAUTH_SCOPE_FULL,
redirect_uri: Object.assign(new URL(window.location.origin), { hostname: '127.0.0.1' }).href,
})}`;
}
return `https://${window.location.host}/oauth-client-metadata.json`;
}
/* ── Utilities ── */
const ADJS = ['bold','calm','cool','dark','fair','fast','keen','lean','neat','pure','rare','safe','sharp','swift','warm','wise'];
const NOUNS = ['aurora','badge','beacon','blaze','cipher','crest','echo','falcon','glint','haven','latch','nexus','pulse','quill','ridge','sigil','spark','torch','verge','woven'];
export function randomName() {
const rand = (arr) => arr[Math.floor(Math.random() * arr.length)];
return `${rand(ADJS)}-${rand(NOUNS)}`;
}
export function parseRkey(uri) {
const parts = uri.split('/');
return parts[parts.length - 1];
}
const FRAGMENT_KINDS = { plc: 'requester', bdr: 'bidder', key: 'key' };
const FRAGMENT_DID = /^did:(?:plc|key):\S+$/;
export function parseFragment(raw) {
let hash = raw || '';
try { hash = decodeURIComponent(hash); } catch {}
if (!hash) return null;
if (FRAGMENT_DID.test(hash)) {
return { did: hash, kind: hash.startsWith('did:key:') ? 'key' : null, nonce: null, service: null };
}
const params = {};
for (const part of hash.split('&')) {
const i = part.indexOf('=');
if (i > 0) params[part.slice(0, i)] = part.slice(i + 1);
}
for (const [k, kind] of Object.entries(FRAGMENT_KINDS)) {
if (FRAGMENT_DID.test(params[k] || '')) {
return { did: params[k], kind, nonce: params.n || null, service: params.s || null };
}
}
try {
const inner = new URL(hash).hash.slice(1);
if (inner) return parseFragment(inner);
} catch {}
return null;
}
export function getHashLink() {
const link = parseFragment(window.location.hash.slice(1));
log('debug', 'hash', 'getHashLink', { did: link?.did || null, kind: link?.kind || null, hasNonce: !!link?.nonce, service: link?.service || null });
return link;
}
export function getHashDid() {
return getHashLink()?.did || null;
}
export function getHashKind() {
if (window.location.hash.slice(1).startsWith('oauth=')) return 'oauth';
return getHashLink()?.kind || null;
}
export function getHashOauthParams() {
const hash = window.location.hash.slice(1);
if (!hash.startsWith('oauth=')) return null;
const params = {};
for (const part of hash.split('&')) {
const [k, v] = part.split('=');
if (k && v) params[decodeURIComponent(k)] = decodeURIComponent(v);
}
log('info', 'hash', 'getHashOauthParams', { oauth: params.oauth || null, hasNonce: !!params.n });
return params.oauth ? params : null;
}
export function associationUrl(didKey) {
return `${window.location.origin}${window.location.pathname}#${encodeURIComponent(didKey)}`;
}
/* ── Hash survival through OAuth redirect ── */
const OAUTH_HASH_KEY = 'dka-oauth-hash';
export function loginHashState() {
const hash = window.location.hash.slice(1);
return parseFragment(hash) ? `dka:${hash}` : undefined;
}
export function saveHashForLogin() {
const hash = window.location.hash.slice(1);
const oauthParams = getHashOauthParams();
if (parseFragment(hash)) {
sessionStorage.setItem(OAUTH_HASH_KEY, hash);
log('info', 'hash', 'saveHashForLogin:stored', { hash });
} else if (oauthParams) {
sessionStorage.setItem(OAUTH_HASH_KEY, `oauth=${oauthParams.oauth}&n=${oauthParams.n}`);
log('info', 'hash', 'saveHashForLogin:storedOauth', { oauth: oauthParams.oauth });
} else {
log('debug', 'hash', 'saveHashForLogin:noHash');
}
}
export function restoreHashFromLogin() {
const saved = sessionStorage.getItem(OAUTH_HASH_KEY);
if (!saved) {
log('debug', 'hash', 'restoreHashFromLogin:empty');
return null;
}
sessionStorage.removeItem(OAUTH_HASH_KEY);
const current = window.location.hash.slice(1);
if (!saved.startsWith('oauth=') && !parseFragment(current) && !current.startsWith('oauth=')) {
history.replaceState(null, '', `${window.location.pathname}${window.location.search}#${saved}`);
}
log('info', 'hash', 'restoreHashFromLogin:restored', { saved });
return saved;
}
export function clearOAuthHash() {
const had = sessionStorage.getItem(OAUTH_HASH_KEY);
sessionStorage.removeItem(OAUTH_HASH_KEY);
if (had) log('debug', 'hash', 'clearOAuthHash:cleared', { did: had });
}
export function isAlreadyAssociated(records, didKey) {
if (!didKey || !records) { log('debug', 'attest', 'isAlreadyAssociated:noInput'); return false; }
const found = records.some(r => r.value?.keyId === didKey);
log('info', 'attest', 'isAlreadyAssociated', { didKey, recordCount: records.length, found });
return found;
}
/* ── QR scanning ── */
let qrStream = null;
let qrAnimFrame = null;
export function didFromScanValue(value) {
log('debug', 'qr', 'didFromScanValue:input', { valueLen: value?.length || 0 });
const did = parseFragment(value)?.did || null;
if (did) log('info', 'qr', 'didFromScanValue:found', { did });
else log('warn', 'qr', 'didFromScanValue:noDid', { value });
return did;
}
let _fileOnCapture = null;
export function startQRScanner({ onScan, onStatus, containerEl, videoEl }) {
containerEl.style.display = "block";
hideFileBtn(containerEl);
onStatus?.('', '');
const onCapture = (did) => {
onScan(did);
stopQRScanner();
};
// iOS-required video attributes — set before stream touches element
for (const [attr, val] of [['muted', ''], ['playsinline', ''], ['webkit-playsinline', ''], ['autoplay', '']]) {
videoEl.setAttribute(attr, val);
}
videoEl.style.display = '';
// Wait for layout (container just un-hidden, iOS needs computed dimensions)
requestAnimationFrame(() => {
onStatus?.('Requesting camera...', '');
// Create canvas for frame capture
let canvas = containerEl.querySelector('#qr-canvas');
if (!canvas) {
canvas = document.createElement('canvas');
canvas.id = 'qr-canvas';
canvas.style.cssText = 'display:none;';
containerEl.appendChild(canvas);
}
const constraints = { video: { facingMode: "environment", width: { ideal: 640 }, height: { ideal: 480 } } };
navigator.mediaDevices.getUserMedia(constraints)
.then(stream => {
qrStream = stream;
// Detach/re-attach — fixes iOS WebKit rendering blackout (#310349)
videoEl.srcObject = null;
setTimeout(() => {
if (!qrStream) return;
videoEl.onloadedmetadata = () => videoEl.play().catch(() => {});
videoEl.srcObject = qrStream;
}, 80);
onStatus?.('Scanning... point camera at a QR code.', '');
// BarcodeDetector path (Chrome/Edge) — fast native API
if ('BarcodeDetector' in window) {
const detector = new BarcodeDetector({ formats: ['qr_code'] });
const scan = async () => {
if (!qrStream) return;
try {
const barcodes = await detector.detect(videoEl);
if (barcodes.length > 0) {
const did = didFromScanValue(barcodes[0].rawValue);
if (did) { onCapture(did); return; }
onStatus?.('Scanned but not a did:key. Keep scanning.', 'danger');
}
} catch (e) { /* may throw on some frames */ }
if (qrStream) qrAnimFrame = requestAnimationFrame(scan);
};
qrAnimFrame = requestAnimationFrame(scan);
} else {
// Safari/iOS: canvas + jsQR scan loop
const ctx = canvas.getContext('2d', { willReadFrequently: true });
let lastScan = 0;
const SCAN_INTERVAL = 250; // ms between decode attempts
const scan = () => {
if (!qrStream) return;
qrAnimFrame = requestAnimationFrame(scan);
const now = performance.now();
if (now - lastScan < SCAN_INTERVAL) return;
lastScan = now;
if (videoEl.readyState < 2) return; // no frame data yet
try {
canvas.width = videoEl.videoWidth;
canvas.height = videoEl.videoHeight;
if (canvas.width === 0 || canvas.height === 0) return;
ctx.drawImage(videoEl, 0, 0, canvas.width, canvas.height);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const code = jsQR(imageData.data, imageData.width, imageData.height);
if (code) {
const did = didFromScanValue(code.data);
if (did) onCapture(did);
}
} catch (e) { /* skip bad frames */ }
};
qrAnimFrame = requestAnimationFrame(scan);
}
})
.catch((err) => {
if (qrStream) { qrStream.getTracks().forEach(t => t.stop()); qrStream = null; }
const reason = err.name === 'NotAllowedError' ? 'Camera permission denied. ' :
err.name === 'NotFoundError' ? 'No camera found. ' : `Camera error: ${err.message}. `;
onStatus?.(`${reason}Tap "Take Photo" below.`, 'danger');
showFileBtn(containerEl, onCapture, onStatus);
});
});
}
function getFileBtn(containerEl) {
let wrapper = containerEl.querySelector('#qr-file-wrapper');
if (!wrapper) {
wrapper = document.createElement('div');
wrapper.id = 'qr-file-wrapper';
wrapper.style.cssText = 'display:none;margin-top:12px;';
const input = document.createElement('input');
input.type = 'file';
input.id = 'qr-file-input';
input.accept = 'image/*';
input.capture = 'environment';
input.style.cssText = 'display:none;';
const label = document.createElement('label');
label.setAttribute('for', 'qr-file-input');
label.className = 'btn btn-secondary btn-block';
label.style.cssText = 'cursor:pointer;';
label.textContent = 'Take Photo';
wrapper.appendChild(input);
wrapper.appendChild(label);
containerEl.appendChild(wrapper);
input.addEventListener('change', async () => {
const file = input.files?.[0];
if (!file) return;
const statusEl = containerEl.querySelector('#qr-scan-status');
if (statusEl) statusEl.textContent = 'Decoding QR from photo...';
try {
const img = new Image();
img.src = URL.createObjectURL(file);
await new Promise((resolve, reject) => {
img.onload = resolve;
img.onerror = reject;
});
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const code = jsQR(imageData.data, imageData.width, imageData.height);
URL.revokeObjectURL(img.src);
if (code) {
const did = didFromScanValue(code.data);
if (did && _fileOnCapture) {
if (statusEl) { statusEl.textContent = ''; statusEl.style.color = ''; }
_fileOnCapture(did);
return;
}
}
if (statusEl) { statusEl.textContent = 'No did:key found in image. Try again.'; statusEl.style.color = 'var(--danger)'; }
} catch (e) {
if (statusEl) { statusEl.textContent = `Scan failed: ${e.message || e}. Try again.`; statusEl.style.color = 'var(--danger)'; }
}
});
}
return wrapper;
}
function showFileBtn(containerEl, onCapture, onStatus) {
_fileOnCapture = onCapture;
const wrapper = getFileBtn(containerEl);
wrapper.style.display = '';
const input = wrapper.querySelector('#qr-file-input');
input.value = '';
}
function hideFileBtn(containerEl) {
const wrapper = containerEl.querySelector('#qr-file-wrapper');
if (wrapper) wrapper.style.display = 'none';
_fileOnCapture = null;
}
export function stopQRScanner() {
if (qrAnimFrame) {
cancelAnimationFrame(qrAnimFrame);
qrAnimFrame = null;
}
if (qrStream) {
qrStream.getTracks().forEach(t => t.stop());
qrStream = null;
}
const container = document.getElementById("qr-scanner-container");
if (container) {
container.style.display = "none";
hideFileBtn(container);
}
const video = document.getElementById("qr-video");
if (video) {
video.pause();
video.srcObject = null;
video.removeAttribute('src');
video.load(); // Release iOS AVPlayer resources
}
}
/* ── QR generation ── */
export async function generateQrImg(didKey) {
const url = associationUrl(didKey);
const dataUrl = await toDataURL(url, { width: 180, margin: 2, color: { dark: '#000', light: '#fff' } });
const img = document.createElement('img');
img.src = dataUrl;
img.className = 'qr-code-img';
img.alt = `QR code for ${didKey}`;
img.title = url;
return img;
}
/* ── ATProto CRUD ── */
export async function fetchRecords(agent) {
let records = [];
let cursor = undefined;
while (cursor === undefined || cursor != null) {
const res = await agent.com.atproto.repo.listRecords({
repo: agent.did,
collection: BADGE_BLUE_KEYS_NSID,
cursor,
});
if (!res.success) throw new Error(JSON.stringify(res));
records.push(...res.data.records);
cursor = typeof res.data.cursor === "string" ? res.data.cursor : null;
}
return records;
}
export async function doAssociate(agent, { didKey, name, service }) {
const res = await agent.com.atproto.repo.createRecord({
repo: agent.did,
collection: BADGE_BLUE_KEYS_NSID,
record: {
$type: BADGE_BLUE_KEYS_NSID,
keyId: didKey,
name: name || randomName(),
challenge: agent.did,
service: service || '*',
createdAt: new Date().toISOString(),
},
});
if (!res.success) throw new Error(JSON.stringify(res));
return res;
}
export function claimRKey(service, did) {
return `${service}-${did.replaceAll(':', '-')}`;
}
async function putClaim(agent, rkey, record) {
const res = await agent.com.atproto.repo.putRecord({
repo: agent.did,
collection: BADGE_BLUE_KEYS_NSID,
rkey,
record,
});
if (!res.success) throw new Error(JSON.stringify(res));
return res;
}
export async function doClaimAssociate(agent, { did, service, nonce }) {
const rkey = claimRKey(service, did);
const repo = agent.com.atproto.repo;
const existing = await repo.getRecord({ repo: agent.did, collection: BADGE_BLUE_KEYS_NSID, rkey }).catch(() => null);
if (existing?.data?.value?.nonce === nonce) {
log('info', 'attest', 'doClaimAssociate:alreadyClaimed', { did, service, uri: existing.data.uri });
return { uri: existing.data.uri };
}
const res = await repo.putRecord({
repo: agent.did,
collection: BADGE_BLUE_KEYS_NSID,
rkey,
record: {
$type: BADGE_BLUE_KEYS_NSID,
keyId: did,
challenge: agent.did,
service,
nonce,
name: `${service.split('_')[0]}-${did.slice(-8)}`,
createdAt: new Date().toISOString(),
},
});
if (!res.success) throw new Error(JSON.stringify(res));
log('info', 'attest', 'doClaimAssociate:written', { did, service, uri: res.data.uri });
return { uri: res.data.uri };
}
export async function doRequesterAssociate(agent, requesterDid) {
// Resolve requester DID doc to find #requester_associate service
let serviceEndpoint = null;
try {
const didDoc = await (await fetch(
requesterDid.startsWith('did:web:')
? `https://${requesterDid.slice('did:web:'.length)}/.well-known/did.json`
: `https://plc.directory/${requesterDid}`
)).json();
const svc = (didDoc.service || []).find((s) => s.id === '#requester_associate' || s.id === 'requester_associate');
serviceEndpoint = svc?.serviceEndpoint;
} catch { /* fallback */ }
if (!serviceEndpoint) {
throw new Error('Requester has no #requester_associate service');
}
// Call associateConfirm via PDS proxy with retry
const client = new XrpcClient(agent, ASSOCIATE_LEXICON_STUBS);
let lastErr = null;
for (let attempt = 0; attempt < 5; attempt++) {
if (attempt > 0) await new Promise((r) => setTimeout(r, 3000));
try {
const res = await client.call(ASSOCIATE_CONFIRM_NSID, {}, {}, {
headers: { 'atproto-proxy': `${requesterDid}#requester_associate` },
});
if (res.success) {
// CLI confirmed — now create the key association record
const keyRes = await putClaim(agent, claimRKey('requester_associate', requesterDid), {
$type: BADGE_BLUE_KEYS_NSID,
keyId: requesterDid,
name: `requester-${requesterDid.slice(-8)}`,
challenge: agent.did,
service: 'requester_associate',
createdAt: new Date().toISOString(),
});
return { ok: true, requesterDid: res.data.requesterDid, associationUri: keyRes.data.uri };
}
lastErr = new Error(JSON.stringify(res.data));
} catch (err) {
lastErr = err;
}
}
throw lastErr || new Error('associateConfirm failed after retries');
}
export async function doBidderAssociate(agent, bidderDid) {
let serviceEndpoint = null;
try {
const didDoc = await (await fetch(
bidderDid.startsWith('did:web:')
? `https://${bidderDid.slice('did:web:'.length)}/.well-known/did.json`
: `https://plc.directory/${bidderDid}`
)).json();
const svc = (didDoc.service || []).find((s) => s.id === '#bidder_associate' || s.id === 'bidder_associate');
serviceEndpoint = svc?.serviceEndpoint;
} catch { /* fallback */ }
if (!serviceEndpoint) {
throw new Error('Bidder has no #bidder_associate service');
}
const client = new XrpcClient(agent, ASSOCIATE_LEXICON_STUBS);
let lastErr = null;
for (let attempt = 0; attempt < 5; attempt++) {
if (attempt > 0) await new Promise((r) => setTimeout(r, 3000));
try {
const res = await client.call(ASSOCIATE_CONFIRM_NSID, {}, {}, {
headers: { 'atproto-proxy': `${bidderDid}#bidder_associate` },
});
if (res.success) {
const keyRes = await putClaim(agent, claimRKey('bidder_associate', bidderDid), {
$type: BADGE_BLUE_KEYS_NSID,
keyId: bidderDid,
name: `bidder-${bidderDid.slice(-8)}`,
challenge: agent.did,
service: 'bidder_associate',
createdAt: new Date().toISOString(),
});
return { ok: true, bidderDid: res.data.requesterDid, associationUri: keyRes.data.uri };
}
lastErr = new Error(JSON.stringify(res.data));
} catch (err) {
lastErr = err;
}
}
throw lastErr || new Error('associateConfirm failed after retries');
}
export async function doRename(agent, rec, rkey, newName) {
const updated = { ...rec.value, name: newName };
const res = await agent.com.atproto.repo.putRecord({
repo: agent.did,
collection: BADGE_BLUE_KEYS_NSID,
rkey,
record: updated,
});
if (!res.success) throw new Error(JSON.stringify(res));
}
export async function doDelete(agent, rkey) {
const res = await agent.com.atproto.repo.deleteRecord({
repo: agent.did,
collection: BADGE_BLUE_KEYS_NSID,
rkey,
});
if (!res.success) throw new Error(JSON.stringify(res));
}
/* ── OAuth session init ── */
export async function initSession() {
const clientId = buildClientID();
const oac = await BrowserOAuthClient.load({
clientId,
handleResolver: 'https://bsky.social',
sessionStore: {
async get(key) { const v = localStorage.getItem(key); return v ? JSON.parse(v) : undefined; },
async set(key, val) { localStorage.setItem(key, JSON.stringify(val)); },
async del(key) { localStorage.removeItem(key); },
},
});
// A stored OAuth session can go stale — revoked by the PDS, consumed by an
// earlier session transfer, refresh token expired. init() or getSession()
// then throws ("Session expired"). Never hard-fail the page: clear the dead
// session and degrade to logged-out so the QR / session-transfer flow still
// renders.
const clearStoredSessions = () => {
const PREFIX = '@@atproto/oauth-client-browser';
for (const key of Object.keys(localStorage)) {
if (key.startsWith(PREFIX)) localStorage.removeItem(key);
}
};
let result;
try {
result = await oac.init();
} catch (err) {
log('error', 'oauth', 'initSession:initFailed', { error: String(err) });
clearStoredSessions();
return { oac, agent: null, sessionHandle: null };
}
if (result) {
const { session, state } = result;
const isFreshLogin = state != null;
log('info', 'oauth', isFreshLogin ? 'initSession:freshLogin' : 'initSession:restored', {
sub: session.sub, hasState: isFreshLogin,
});
// Restore hash from OAuth state (carried through redirect protocol-level).
if (state && typeof state === 'string' && state.startsWith('dka-oauth:')) {
// State format: dka-oauth:did:plc:xxx:32hexnonce
// DID contains colons, so split on last ':'
const inner = state.slice(10);
const lastColon = inner.lastIndexOf(':');
const cliDid = inner.slice(0, lastColon);
const nonce = inner.slice(lastColon + 1);
sessionStorage.setItem('dka-oauth-hash', `oauth=${cliDid}&n=${nonce}`);
log('info', 'oauth', 'initSession:hashFromStateOauth', { cliDid, nonce });
} else if (state && typeof state === 'string' && state.startsWith('dka:')) {
const hashDid = state.slice(4);
sessionStorage.setItem('dka-oauth-hash', hashDid);
log('info', 'oauth', 'initSession:hashFromState', { hashDid });
} else if (state) {
log('debug', 'oauth', 'initSession:stateNoDkaPrefix', { statePrefix: state.substring(0, 10) });
}
const agent = new Agent(session);
let res;
try {
res = await agent.com.atproto.server.getSession();
} catch (err) {
// Stale session: PDS rejected it (e.g. "Session expired"). Drop it and
// treat as logged-out instead of throwing to the whole app.
log('error', 'oauth', 'initSession:getSessionFailed', { error: String(err) });
clearStoredSessions();
return { oac, agent: null, sessionHandle: null };
}
if (!res.success) {
log('error', 'oauth', 'initSession:getSessionFailed', { error: JSON.stringify(res) });
clearStoredSessions();
return { oac, agent: null, sessionHandle: null };
}
log('info', 'oauth', 'initSession:ok', { handle: res.data.handle });
return { oac, agent, sessionHandle: res.data.handle };
}
log('info', 'oauth', 'initSession:noSession');
return { oac, agent: null, sessionHandle: null };
}
export async function doLogin(oac, identifier, state) {
log('info', 'oauth', 'doLogin:start', { identifier, hasHashState: state?.startsWith('dka:') });
await oac.signIn(identifier, {
state: state || 'some value needed later',
signal: new AbortController().signal,
});
}