// Enhanced setData with automatic authentication
async function setData(
elementId: string,
newData: any,
options: { action?: string } = {}
) {
const action = options.action || "write"; // Default action
if (window.playhtmlAuth?.identity) {
try {
// Check permissions first
const hasPermission = await checkPermission(
elementId,
action,
window.playhtmlAuth.identity
);
if (!hasPermission) {
throw new Error("Permission denied");
}
// Automatically sign the data change
const signedChange = await createSignedAction(
action,
elementId,
newData,
window.playhtmlAuth.identity
);
// Apply to CRDT with temporary auth data
applyDataChange({
type: "crdt_update",
elementId,
data: {
...newData,
_temp_auth: signedChange,
},
});
} catch (error) {
console.error("Failed to perform action:", error);
showUserFeedback(`Unable to ${action}: ${error.message}`);
}
} else {
// No identity - check if action is allowed for "everyone"
const hasPermission = await checkPermission(elementId, action);
if (hasPermission) {
// Apply change without authentication
applyDataChange({
type: "crdt_update",
elementId,
data: newData,
});
} else {
showUserFeedback("Please connect your PlayHTML identity to interact");
}
}
}
async function createSignedAction(
action: string,
elementId: string,
data: any,
identity: PlayHTMLIdentity
): Promise<SignedAction> {
const payload = {
action,
elementId,
data,
timestamp: Date.now(),
nonce: crypto.randomUUID(),
};
const message = JSON.stringify(payload);
const signature = await signMessage(message, identity.privateKey);
return {
...payload,
signature,
publicKey: identity.publicKey,