From 441f47d50ef177d7d2298e2fbbec78984d1c46f5 Mon Sep 17 00:00:00 2001 From: shocknet-justin Date: Sat, 14 Jun 2025 17:19:47 -0400 Subject: [PATCH 01/24] extrnal offer management --- src/nostrMiddleware.ts | 11 +- src/services/managementManager.ts | 176 ++++++++++++++++++ src/services/nostr/handler.ts | 2 +- .../storage/entity/ManagementGrant.ts | 24 +++ src/services/storage/entity/UserOffer.ts | 3 + ...1749933500426-AddOfferManagingAppPubKey.ts | 14 ++ .../1749934345873-CreateManagementGrant.ts | 50 +++++ 7 files changed, 278 insertions(+), 2 deletions(-) create mode 100644 src/services/managementManager.ts create mode 100644 src/services/storage/entity/ManagementGrant.ts create mode 100644 src/services/storage/migrations/1749933500426-AddOfferManagingAppPubKey.ts create mode 100644 src/services/storage/migrations/1749934345873-CreateManagementGrant.ts diff --git a/src/nostrMiddleware.ts b/src/nostrMiddleware.ts index a21aee22..e24dce8f 100644 --- a/src/nostrMiddleware.ts +++ b/src/nostrMiddleware.ts @@ -5,6 +5,7 @@ import * as Types from '../proto/autogenerated/ts/types.js' import NewNostrTransport, { NostrRequest } from '../proto/autogenerated/ts/nostr_transport.js'; import { ERROR, getLogger } from "./services/helpers/logger.js"; import { NdebitData, NofferData } from "@shocknet/clink-sdk"; +import { ManagementManager } from "./services/managementManager.js"; export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSettings: NostrSettings, onClientEvent: (e: { requestId: string }, fromPub: string) => void): { Stop: () => void, Send: NostrSend, Ping: () => Promise } => { const log = getLogger({}) @@ -37,7 +38,11 @@ export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSett }, logger: { log: console.log, error: err => log(ERROR, err) }, }) - const nostr = new Nostr(nostrSettings, mainHandler.utils, event => { + + let nostr: Nostr; + const managementManager = new ManagementManager((...args) => nostr.Send(...args), nostrSettings); + + nostr = new Nostr(nostrSettings, mainHandler.utils, event => { let j: NostrRequest try { j = JSON.parse(event.content) @@ -54,6 +59,9 @@ export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSett const debitReq = j as NdebitData mainHandler.debitManager.handleNip68Debit(debitReq, event) return + } else if (event.kind === 21003) { + managementManager.handleRequest(event); + return; } if (!j.rpcName) { onClientEvent(j as { requestId: string }, event.pub) @@ -67,6 +75,7 @@ export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSett nostr.Send({ type: 'app', appId: event.appId }, { type: 'content', pub: event.pub, content: JSON.stringify({ ...res, requestId: j.requestId }) }) }, event.startAtNano, event.startAtMs) }) + return { Stop: () => nostr.Stop, Send: (...args) => nostr.Send(...args), Ping: () => nostr.Ping() } } diff --git a/src/services/managementManager.ts b/src/services/managementManager.ts new file mode 100644 index 00000000..7ad85a55 --- /dev/null +++ b/src/services/managementManager.ts @@ -0,0 +1,176 @@ +import { NostrEvent } from "@shocknet/clink-sdk"; +import { User } from "./storage/entity/User"; +import { ManagementGrant } from "./storage/entity/ManagementGrant"; +import { validateEvent } from "nostr-tools"; +import { getRepository } from "typeorm"; +import { UserOffer } from "./storage/entity/UserOffer"; +import { NostrSend, NostrSettings } from "./nostr/handler"; + +export class ManagementManager { + private nostrSend: NostrSend; + private settings: NostrSettings; + + constructor(nostrSend: NostrSend, settings: NostrSettings) { + this.nostrSend = nostrSend; + this.settings = settings; + } + + /** + * Handles an incoming CLINK Manage request + * @param event The raw Nostr event + */ + public async handleRequest(event: NostrEvent) { + const app = this.settings.apps.find(a => a.appId === event.appId); + if (!app) { + console.error(`App with id ${event.appId} not found in settings`); + return; // Cannot proceed + } + const appPubkey = app.publicKey; + + // Validate event + const isValid = validateEvent(event); + if (!isValid) { + console.error("Invalid event"); + return; + } + + // Check grant + const userIdTag = event.tags.find((t: string[]) => t[0] === 'p'); + if (!userIdTag) { + console.error("No user specified in event"); + return; + } + const userId = userIdTag[1]; + const requestingPubkey = event.pubkey; + + const grantRepo = getRepository(ManagementGrant); + const grant = await grantRepo.findOne({ where: { user_id: userId, app_pubkey: appPubkey } }); + + if (!grant) { + console.error(`No management grant found for app ${appPubkey} and user ${userId}`); + this.sendErrorResponse(requestingPubkey, `No management grant found for app`, app); + return; + } + + if (grant.expires_at && grant.expires_at.getTime() < Date.now()) { + console.error(`Management grant for app ${appPubkey} and user ${userId} has expired`); + this.sendErrorResponse(requestingPubkey, `Management grant has expired`, app); + return; + } + + // Perform action + const actionTag = event.tags.find((t: string[]) => t[0] === 'a'); + if (!actionTag) { + console.error("No action specified in event"); + return; + } + + const action = actionTag[1]; + const offerRepo = getRepository(UserOffer); + + switch (action) { + case "create": + const createDetailsTag = event.tags.find((t: string[]) => t[0] === 'd'); + if (!createDetailsTag || !createDetailsTag[1]) { + console.error("No details provided for create action"); + return; + } + try { + const offerData = JSON.parse(createDetailsTag[1]); + const newOffer = offerRepo.create({ + ...offerData, + user_id: userId, + managing_app_pubkey: appPubkey + }); + await offerRepo.save(newOffer); + this.sendSuccessResponse(requestingPubkey, "Offer created successfully", app); + } catch (e) { + console.error("Failed to parse or save offer data", e); + this.sendErrorResponse(requestingPubkey, "Failed to create offer", app); + } + break; + case "update": + const updateTags = event.tags.filter((t: string[]) => t[0] === 'd'); + if (updateTags.length < 2) { + console.error("Insufficient details for update action"); + return; + } + const offerIdToUpdate = updateTags[0][1]; + const updateData = JSON.parse(updateTags[1][1]); + + try { + const existingOffer = await offerRepo.findOne({where: { offer_id: offerIdToUpdate }}); + if (!existingOffer) { + console.error(`Offer ${offerIdToUpdate} not found`); + return; + } + + if (existingOffer.managing_app_pubkey !== appPubkey) { + console.error(`App ${appPubkey} not authorized to update offer ${offerIdToUpdate}`); + return; + } + + offerRepo.merge(existingOffer, updateData); + await offerRepo.save(existingOffer); + this.sendSuccessResponse(requestingPubkey, "Offer updated successfully", app); + } catch (e) { + console.error("Failed to update offer data", e); + this.sendErrorResponse(requestingPubkey, "Failed to update offer", app); + } + break; + case "delete": + const deleteDetailsTag = event.tags.find((t: string[]) => t[0] === 'd'); + if (!deleteDetailsTag || !deleteDetailsTag[1]) { + console.error("No details provided for delete action"); + return; + } + const offerIdToDelete = deleteDetailsTag[1]; + + try { + const offerToDelete = await offerRepo.findOne({where: { offer_id: offerIdToDelete }}); + if (!offerToDelete) { + console.error(`Offer ${offerIdToDelete} not found`); + return; + } + + if (offerToDelete.managing_app_pubkey !== appPubkey) { + console.error(`App ${appPubkey} not authorized to delete offer ${offerIdToDelete}`); + return; + } + + await offerRepo.remove(offerToDelete); + this.sendSuccessResponse(requestingPubkey, "Offer deleted successfully", app); + } catch (e) { + console.error("Failed to delete offer", e); + this.sendErrorResponse(requestingPubkey, "Failed to delete offer", app); + } + break; + default: + console.error(`Unknown action: ${action}`); + this.sendErrorResponse(requestingPubkey, `Unknown action: ${action}`, app); + return; + } + } + + private sendSuccessResponse(recipient: string, message: string, app: {publicKey: string, appId: string}) { + const responseEvent = { + kind: 21003, + pubkey: app.publicKey, + created_at: Math.floor(Date.now() / 1000), + content: JSON.stringify({ status: "success", message }), + tags: [['p', recipient]], + }; + this.nostrSend({ type: 'app', appId: app.appId }, { type: 'event', event: responseEvent, encrypt: { toPub: recipient } }); + } + + private sendErrorResponse(recipient: string, message: string, app: {publicKey: string, appId: string}) { + const responseEvent = { + kind: 21003, + pubkey: app.publicKey, + created_at: Math.floor(Date.now() / 1000), + content: JSON.stringify({ status: "error", message }), + tags: [['p', recipient]], + }; + this.nostrSend({ type: 'app', appId: app.appId }, { type: 'event', event: responseEvent, encrypt: { toPub: recipient } }); + } +} \ No newline at end of file diff --git a/src/services/nostr/handler.ts b/src/services/nostr/handler.ts index 5fa8b430..50496cc7 100644 --- a/src/services/nostr/handler.ts +++ b/src/services/nostr/handler.ts @@ -124,7 +124,7 @@ const sendToNostr: NostrSend = (initiator, data, relays) => { subProcessHandler.Send(initiator, data, relays) } send({ type: 'ready' }) -const supportedKinds = [21000, 21001, 21002] +const supportedKinds = [21000, 21001, 21002, 21003] export default class Handler { pool = new SimplePool() settings: NostrSettings diff --git a/src/services/storage/entity/ManagementGrant.ts b/src/services/storage/entity/ManagementGrant.ts new file mode 100644 index 00000000..16a3499f --- /dev/null +++ b/src/services/storage/entity/ManagementGrant.ts @@ -0,0 +1,24 @@ +import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, ManyToOne, JoinColumn } from "typeorm"; +import { User } from "./User"; + +@Entity("management_grants") +export class ManagementGrant { + @PrimaryGeneratedColumn("uuid") + id: string; + + @Column() + user_id: string; + + @ManyToOne(() => User) + @JoinColumn({ name: "user_id", referencedColumnName: "user_id" }) + user: User; + + @Column() + app_pubkey: string; + + @CreateDateColumn() + created_at: Date; + + @Column({ type: 'timestamp', nullable: true }) + expires_at: Date; +} \ No newline at end of file diff --git a/src/services/storage/entity/UserOffer.ts b/src/services/storage/entity/UserOffer.ts index 409c4e8d..2d7d4bec 100644 --- a/src/services/storage/entity/UserOffer.ts +++ b/src/services/storage/entity/UserOffer.ts @@ -13,6 +13,9 @@ export class UserOffer { @Column({ unique: true, nullable: false }) offer_id: string + @Column({ nullable: true }) + managing_app_pubkey: string | null + @Column() label: string diff --git a/src/services/storage/migrations/1749933500426-AddOfferManagingAppPubKey.ts b/src/services/storage/migrations/1749933500426-AddOfferManagingAppPubKey.ts new file mode 100644 index 00000000..2585e67f --- /dev/null +++ b/src/services/storage/migrations/1749933500426-AddOfferManagingAppPubKey.ts @@ -0,0 +1,14 @@ +import { MigrationInterface, QueryRunner } from "typeorm" + +export class AddOfferManagingAppPubKey1749933500426 implements MigrationInterface { + name = 'AddOfferManagingAppPubKey1749933500426' + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE "user_offer" ADD "managing_app_pubkey" character varying`); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE "user_offer" DROP COLUMN "managing_app_pubkey"`); + } + +} diff --git a/src/services/storage/migrations/1749934345873-CreateManagementGrant.ts b/src/services/storage/migrations/1749934345873-CreateManagementGrant.ts new file mode 100644 index 00000000..a14838a1 --- /dev/null +++ b/src/services/storage/migrations/1749934345873-CreateManagementGrant.ts @@ -0,0 +1,50 @@ +import { MigrationInterface, QueryRunner, Table, TableForeignKey } from "typeorm" + +export class CreateManagementGrant1749934345873 implements MigrationInterface { + name = 'CreateManagementGrant1749934345873' + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.createTable(new Table({ + name: "management_grants", + columns: [ + { + name: "id", + type: "varchar", + isPrimary: true, + isGenerated: true, + generationStrategy: "uuid" + }, + { + name: "user_id", + type: "varchar" + }, + { + name: "app_pubkey", + type: "varchar" + }, + { + name: "created_at", + type: "timestamp", + default: "CURRENT_TIMESTAMP" + }, + { + name: "expires_at", + type: "timestamp", + isNullable: true + } + ] + })); + + await queryRunner.createForeignKey("management_grants", new TableForeignKey({ + columnNames: ["user_id"], + referencedColumnNames: ["user_id"], + referencedTableName: "user", + onDelete: "CASCADE" + })); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.dropTable("management_grants"); + } + +} From cfe6aa200bb0e1afb1656a4aa706e90cd23f544e Mon Sep 17 00:00:00 2001 From: shocknet-justin Date: Sat, 14 Jun 2025 17:40:11 -0400 Subject: [PATCH 02/24] event from tools --- src/services/managementManager.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/services/managementManager.ts b/src/services/managementManager.ts index 7ad85a55..8ee4fcf2 100644 --- a/src/services/managementManager.ts +++ b/src/services/managementManager.ts @@ -1,11 +1,14 @@ -import { NostrEvent } from "@shocknet/clink-sdk"; -import { User } from "./storage/entity/User"; -import { ManagementGrant } from "./storage/entity/ManagementGrant"; -import { validateEvent } from "nostr-tools"; import { getRepository } from "typeorm"; +import { User } from "./storage/entity/User"; import { UserOffer } from "./storage/entity/UserOffer"; +import { validateEvent, type Event as BaseNostrEvent } from "nostr-tools"; +import { ManagementGrant } from "./storage/entity/ManagementGrant"; import { NostrSend, NostrSettings } from "./nostr/handler"; +type NostrEvent = BaseNostrEvent & { + appId: string; +}; + export class ManagementManager { private nostrSend: NostrSend; private settings: NostrSettings; From 6c6121b5040157b4d4213f2a7f34d27383f5c0e5 Mon Sep 17 00:00:00 2001 From: shocknet-justin Date: Sat, 14 Jun 2025 21:28:33 -0400 Subject: [PATCH 03/24] event fix? --- src/services/managementManager.ts | 14 +------------- src/services/nostr/handler.ts | 29 +++++++++++++++++++---------- 2 files changed, 20 insertions(+), 23 deletions(-) diff --git a/src/services/managementManager.ts b/src/services/managementManager.ts index 8ee4fcf2..6d30615e 100644 --- a/src/services/managementManager.ts +++ b/src/services/managementManager.ts @@ -1,13 +1,8 @@ import { getRepository } from "typeorm"; import { User } from "./storage/entity/User"; import { UserOffer } from "./storage/entity/UserOffer"; -import { validateEvent, type Event as BaseNostrEvent } from "nostr-tools"; import { ManagementGrant } from "./storage/entity/ManagementGrant"; -import { NostrSend, NostrSettings } from "./nostr/handler"; - -type NostrEvent = BaseNostrEvent & { - appId: string; -}; +import { NostrEvent, NostrSend, NostrSettings } from "./nostr/handler.js"; export class ManagementManager { private nostrSend: NostrSend; @@ -30,13 +25,6 @@ export class ManagementManager { } const appPubkey = app.publicKey; - // Validate event - const isValid = validateEvent(event); - if (!isValid) { - console.error("Invalid event"); - return; - } - // Check grant const userIdTag = event.tags.find((t: string[]) => t[0] === 'p'); if (!userIdTag) { diff --git a/src/services/nostr/handler.ts b/src/services/nostr/handler.ts index 50496cc7..ce064bc7 100644 --- a/src/services/nostr/handler.ts +++ b/src/services/nostr/handler.ts @@ -26,15 +26,16 @@ export type NostrSettings = { clients: ClientInfo[] maxEventContentLength: number } -export type NostrEvent = { - id: string - pub: string - content: string - appId: string - startAtNano: string - startAtMs: number - kind: number -} +export type NostrEvent = Event & { + /** Identifier of the application as defined in NostrSettings.apps */ + appId: string; + /** High-resolution timer capture when processing began (BigInt serialized as string to keep JSON friendly) */ + startAtNano: string; + /** wall-clock millis when processing began */ + startAtMs: number; + /** Convenience duplicate of the sender pubkey (e.pubkey) kept for backwards-compat */ + pub: string; +}; type SettingsRequest = { type: 'settings' @@ -216,7 +217,15 @@ export default class Handler { return } - this.eventCallback({ id: eventId, content, pub: e.pubkey, appId: app.appId, startAtNano, startAtMs, kind: e.kind }) + const nostrEvent: NostrEvent = { + ...e, + content, + appId: app.appId, + startAtNano, + startAtMs, + pub: e.pubkey, + } + this.eventCallback(nostrEvent) } async Send(initiator: SendInitiator, data: SendData, relays?: string[]) { From d7cb1c38f33d9fce8edd4e0ac168ef15a48c14f3 Mon Sep 17 00:00:00 2001 From: shocknet-justin Date: Sat, 14 Jun 2025 21:36:03 -0400 Subject: [PATCH 04/24] column type --- src/services/storage/entity/UserOffer.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/services/storage/entity/UserOffer.ts b/src/services/storage/entity/UserOffer.ts index 2d7d4bec..833e6ca9 100644 --- a/src/services/storage/entity/UserOffer.ts +++ b/src/services/storage/entity/UserOffer.ts @@ -13,7 +13,7 @@ export class UserOffer { @Column({ unique: true, nullable: false }) offer_id: string - @Column({ nullable: true }) + @Column({ type: "text", nullable: true }) managing_app_pubkey: string | null @Column() From 6a1cedd71870c2de8d336b8a501992459fc10927 Mon Sep 17 00:00:00 2001 From: shocknet-justin Date: Sun, 15 Jun 2025 12:55:20 -0400 Subject: [PATCH 05/24] move stuff --- src/nostrMiddleware.ts | 7 +- src/services/main/index.ts | 10 +- src/services/main/managementManager.ts | 195 ++++++++++++++++++++++ src/services/managementManager.ts | 167 ------------------ src/services/storage/index.ts | 3 + src/services/storage/managementStorage.ts | 13 ++ 6 files changed, 222 insertions(+), 173 deletions(-) create mode 100644 src/services/main/managementManager.ts delete mode 100644 src/services/managementManager.ts create mode 100644 src/services/storage/managementStorage.ts diff --git a/src/nostrMiddleware.ts b/src/nostrMiddleware.ts index e24dce8f..aa448295 100644 --- a/src/nostrMiddleware.ts +++ b/src/nostrMiddleware.ts @@ -5,7 +5,7 @@ import * as Types from '../proto/autogenerated/ts/types.js' import NewNostrTransport, { NostrRequest } from '../proto/autogenerated/ts/nostr_transport.js'; import { ERROR, getLogger } from "./services/helpers/logger.js"; import { NdebitData, NofferData } from "@shocknet/clink-sdk"; -import { ManagementManager } from "./services/managementManager.js"; +import { ManagementManager } from "./services/main/managementManager.js"; export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSettings: NostrSettings, onClientEvent: (e: { requestId: string }, fromPub: string) => void): { Stop: () => void, Send: NostrSend, Ping: () => Promise } => { const log = getLogger({}) @@ -40,7 +40,8 @@ export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSett }) let nostr: Nostr; - const managementManager = new ManagementManager((...args) => nostr.Send(...args), nostrSettings); + const managementManager = new ManagementManager((...args: Parameters) => nostr.Send(...args), nostrSettings, mainHandler.storage.managementStorage); + mainHandler.managementManager = managementManager; nostr = new Nostr(nostrSettings, mainHandler.utils, event => { let j: NostrRequest @@ -76,7 +77,7 @@ export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSett }, event.startAtNano, event.startAtMs) }) - return { Stop: () => nostr.Stop, Send: (...args) => nostr.Send(...args), Ping: () => nostr.Ping() } + return { Stop: () => nostr.Stop, Send: (...args: Parameters) => nostr.Send(...args), Ping: () => nostr.Ping() } } diff --git a/src/services/main/index.ts b/src/services/main/index.ts index 42432fba..9d7f09bf 100644 --- a/src/services/main/index.ts +++ b/src/services/main/index.ts @@ -25,6 +25,7 @@ import { defaultInvoiceExpiry } from "../storage/paymentStorage.js" import { DebitManager } from "./debitManager.js" import { OfferManager } from "./offerManager.js" import webRTC from "../webRTC/index.js" +import { ManagementManager } from "./managementManager.js" type UserOperationsSub = { id: string @@ -51,17 +52,16 @@ export default class { liquidityProvider: LiquidityProvider debitManager: DebitManager offerManager: OfferManager + managementManager?: ManagementManager utils: Utils rugPullTracker: RugPullTracker unlocker: Unlocker //webRTC: webRTC nostrSend: NostrSend = () => { getLogger({})("nostr send not initialized yet") } nostrProcessPing: (() => Promise) | null = null - constructor(settings: MainSettings, storage: Storage, adminManager: AdminManager, utils: Utils, unlocker: Unlocker) { + constructor(settings: MainSettings, utils: Utils, unlocker: Unlocker) { this.settings = settings - this.storage = storage this.utils = utils - this.adminManager = adminManager this.unlocker = unlocker const updateProviderBalance = (b: number) => this.storage.liquidityStorage.IncrementTrackedProviderBalance('lnPub', settings.liquiditySettings.liquidityProviderPub, b) this.liquidityProvider = new LiquidityProvider(settings.liquiditySettings.liquidityProviderPub, this.utils, this.invoicePaidCb, updateProviderBalance) @@ -340,6 +340,10 @@ export default class { log({ unsigned: event }) this.nostrSend({ type: 'app', appId: invoice.linkedApplication.app_id }, { type: 'event', event }, zapInfo.relays || undefined) } + + async Start() { + // ... existing code ... + } } diff --git a/src/services/main/managementManager.ts b/src/services/main/managementManager.ts new file mode 100644 index 00000000..f714ada6 --- /dev/null +++ b/src/services/main/managementManager.ts @@ -0,0 +1,195 @@ +import { getRepository } from "typeorm"; +import { User } from "../storage/entity/User.js"; +import { UserOffer } from "../storage/entity/UserOffer.js"; +import { ManagementGrant } from "../storage/entity/ManagementGrant.js"; +import { NostrEvent, NostrSend, NostrSettings } from "../nostr/handler.js"; +import { ManagementStorage } from "../storage/managementStorage.js"; + +export class ManagementManager { + private nostrSend: NostrSend; + private settings: NostrSettings; + private storage: ManagementStorage; + + constructor(nostrSend: NostrSend, settings: NostrSettings, storage: ManagementStorage) { + this.nostrSend = nostrSend; + this.settings = settings; + this.storage = storage; + } + + /** + * Handles an incoming CLINK Manage request + * @param event The raw Nostr event + */ + public async handleRequest(event: NostrEvent) { + const app = this.settings.apps.find((a: any) => a.appId === event.appId); + if (!app) { + console.error(`App with id ${event.appId} not found in settings`); + return; // Cannot proceed + } + + if (!this._validateRequest(event)) { + return; + } + + const grant = await this._checkGrant(event, app.publicKey); + if (!grant) { + this.sendErrorResponse(event.pubkey, "Permission denied.", app); + return; + } + + await this._performAction(event, app); + } + + private _validateRequest(event: NostrEvent): boolean { + // TODO: NIP-44 validation or similar + return true; + } + + private async _checkGrant(event: NostrEvent, appPubkey: string): Promise { + const userIdTag = event.tags.find((t: string[]) => t[0] === 'p'); + if (!userIdTag) { + return null; + } + const userId = userIdTag[1]; + + const grant = await this.storage.getGrant(userId, appPubkey); + + if (!grant || (grant.expires_at && grant.expires_at.getTime() < Date.now())) { + return null; + } + + return grant; + } + + private async _performAction(event: NostrEvent, app: {publicKey: string, appId: string}) { + const actionTag = event.tags.find((t: string[]) => t[0] === 'a'); + if (!actionTag) { + console.error("No action specified in event"); + return; + } + + const action = actionTag[1]; + + switch (action) { + case "create": + await this._createOffer(event, app); + break; + case "update": + await this._updateOffer(event, app); + break; + case "delete": + await this._deleteOffer(event, app); + break; + default: + console.error(`Unknown action: ${action}`); + this.sendErrorResponse(event.pubkey, `Unknown action: ${action}`, app); + } + } + + private async _createOffer(event: NostrEvent, app: {publicKey: string, appId: string}) { + const createDetailsTag = event.tags.find((t: string[]) => t[0] === 'd'); + if (!createDetailsTag || !createDetailsTag[1]) { + console.error("No details provided for create action"); + return; + } + + const userId = event.tags.find((t: string[]) => t[0] === 'p')![1]; + + try { + const offerData = JSON.parse(createDetailsTag[1]); + const offerRepo = getRepository(UserOffer); + const newOffer = offerRepo.create({ + ...offerData, + user_id: userId, + managing_app_pubkey: app.publicKey + }); + await offerRepo.save(newOffer); + this.sendSuccessResponse(event.pubkey, "Offer created successfully", app); + } catch (e) { + console.error("Failed to parse or save offer data", e); + this.sendErrorResponse(event.pubkey, "Failed to create offer", app); + } + } + + private async _updateOffer(event: NostrEvent, app: {publicKey: string, appId: string}) { + const updateTags = event.tags.filter((t: string[]) => t[0] === 'd'); + if (updateTags.length < 2) { + console.error("Insufficient details for update action"); + return; + } + const offerIdToUpdate = updateTags[0][1]; + const updateData = JSON.parse(updateTags[1][1]); + const offerRepo = getRepository(UserOffer); + + try { + const existingOffer = await offerRepo.findOne({where: { offer_id: offerIdToUpdate }}); + if (!existingOffer) { + console.error(`Offer ${offerIdToUpdate} not found`); + return; + } + + if (existingOffer.managing_app_pubkey !== app.publicKey) { + console.error(`App ${app.publicKey} not authorized to update offer ${offerIdToUpdate}`); + return; + } + + offerRepo.merge(existingOffer, updateData); + await offerRepo.save(existingOffer); + this.sendSuccessResponse(event.pubkey, "Offer updated successfully", app); + } catch (e) { + console.error("Failed to update offer data", e); + this.sendErrorResponse(event.pubkey, "Failed to update offer", app); + } + } + + private async _deleteOffer(event: NostrEvent, app: {publicKey: string, appId: string}) { + const deleteDetailsTag = event.tags.find((t: string[]) => t[0] === 'd'); + if (!deleteDetailsTag || !deleteDetailsTag[1]) { + console.error("No details provided for delete action"); + return; + } + const offerIdToDelete = deleteDetailsTag[1]; + const offerRepo = getRepository(UserOffer); + + try { + const offerToDelete = await offerRepo.findOne({where: { offer_id: offerIdToDelete }}); + if (!offerToDelete) { + console.error(`Offer ${offerIdToDelete} not found`); + return; + } + + if (offerToDelete.managing_app_pubkey !== app.publicKey) { + console.error(`App ${app.publicKey} not authorized to delete offer ${offerIdToDelete}`); + return; + } + + await offerRepo.remove(offerToDelete); + this.sendSuccessResponse(event.pubkey, "Offer deleted successfully", app); + } catch (e) { + console.error("Failed to delete offer", e); + this.sendErrorResponse(event.pubkey, "Failed to delete offer", app); + } + } + + private sendSuccessResponse(recipient: string, message: string, app: {publicKey: string, appId: string}) { + const responseEvent = { + kind: 21003, + pubkey: app.publicKey, + created_at: Math.floor(Date.now() / 1000), + content: JSON.stringify({ status: "success", message }), + tags: [['p', recipient]], + }; + this.nostrSend({ type: 'app', appId: app.appId }, { type: 'event', event: responseEvent, encrypt: { toPub: recipient } }); + } + + private sendErrorResponse(recipient: string, message: string, app: {publicKey: string, appId: string}) { + const responseEvent = { + kind: 21003, + pubkey: app.publicKey, + created_at: Math.floor(Date.now() / 1000), + content: JSON.stringify({ status: "error", message }), + tags: [['p', recipient]], + }; + this.nostrSend({ type: 'app', appId: app.appId }, { type: 'event', event: responseEvent, encrypt: { toPub: recipient } }); + } +} \ No newline at end of file diff --git a/src/services/managementManager.ts b/src/services/managementManager.ts deleted file mode 100644 index 6d30615e..00000000 --- a/src/services/managementManager.ts +++ /dev/null @@ -1,167 +0,0 @@ -import { getRepository } from "typeorm"; -import { User } from "./storage/entity/User"; -import { UserOffer } from "./storage/entity/UserOffer"; -import { ManagementGrant } from "./storage/entity/ManagementGrant"; -import { NostrEvent, NostrSend, NostrSettings } from "./nostr/handler.js"; - -export class ManagementManager { - private nostrSend: NostrSend; - private settings: NostrSettings; - - constructor(nostrSend: NostrSend, settings: NostrSettings) { - this.nostrSend = nostrSend; - this.settings = settings; - } - - /** - * Handles an incoming CLINK Manage request - * @param event The raw Nostr event - */ - public async handleRequest(event: NostrEvent) { - const app = this.settings.apps.find(a => a.appId === event.appId); - if (!app) { - console.error(`App with id ${event.appId} not found in settings`); - return; // Cannot proceed - } - const appPubkey = app.publicKey; - - // Check grant - const userIdTag = event.tags.find((t: string[]) => t[0] === 'p'); - if (!userIdTag) { - console.error("No user specified in event"); - return; - } - const userId = userIdTag[1]; - const requestingPubkey = event.pubkey; - - const grantRepo = getRepository(ManagementGrant); - const grant = await grantRepo.findOne({ where: { user_id: userId, app_pubkey: appPubkey } }); - - if (!grant) { - console.error(`No management grant found for app ${appPubkey} and user ${userId}`); - this.sendErrorResponse(requestingPubkey, `No management grant found for app`, app); - return; - } - - if (grant.expires_at && grant.expires_at.getTime() < Date.now()) { - console.error(`Management grant for app ${appPubkey} and user ${userId} has expired`); - this.sendErrorResponse(requestingPubkey, `Management grant has expired`, app); - return; - } - - // Perform action - const actionTag = event.tags.find((t: string[]) => t[0] === 'a'); - if (!actionTag) { - console.error("No action specified in event"); - return; - } - - const action = actionTag[1]; - const offerRepo = getRepository(UserOffer); - - switch (action) { - case "create": - const createDetailsTag = event.tags.find((t: string[]) => t[0] === 'd'); - if (!createDetailsTag || !createDetailsTag[1]) { - console.error("No details provided for create action"); - return; - } - try { - const offerData = JSON.parse(createDetailsTag[1]); - const newOffer = offerRepo.create({ - ...offerData, - user_id: userId, - managing_app_pubkey: appPubkey - }); - await offerRepo.save(newOffer); - this.sendSuccessResponse(requestingPubkey, "Offer created successfully", app); - } catch (e) { - console.error("Failed to parse or save offer data", e); - this.sendErrorResponse(requestingPubkey, "Failed to create offer", app); - } - break; - case "update": - const updateTags = event.tags.filter((t: string[]) => t[0] === 'd'); - if (updateTags.length < 2) { - console.error("Insufficient details for update action"); - return; - } - const offerIdToUpdate = updateTags[0][1]; - const updateData = JSON.parse(updateTags[1][1]); - - try { - const existingOffer = await offerRepo.findOne({where: { offer_id: offerIdToUpdate }}); - if (!existingOffer) { - console.error(`Offer ${offerIdToUpdate} not found`); - return; - } - - if (existingOffer.managing_app_pubkey !== appPubkey) { - console.error(`App ${appPubkey} not authorized to update offer ${offerIdToUpdate}`); - return; - } - - offerRepo.merge(existingOffer, updateData); - await offerRepo.save(existingOffer); - this.sendSuccessResponse(requestingPubkey, "Offer updated successfully", app); - } catch (e) { - console.error("Failed to update offer data", e); - this.sendErrorResponse(requestingPubkey, "Failed to update offer", app); - } - break; - case "delete": - const deleteDetailsTag = event.tags.find((t: string[]) => t[0] === 'd'); - if (!deleteDetailsTag || !deleteDetailsTag[1]) { - console.error("No details provided for delete action"); - return; - } - const offerIdToDelete = deleteDetailsTag[1]; - - try { - const offerToDelete = await offerRepo.findOne({where: { offer_id: offerIdToDelete }}); - if (!offerToDelete) { - console.error(`Offer ${offerIdToDelete} not found`); - return; - } - - if (offerToDelete.managing_app_pubkey !== appPubkey) { - console.error(`App ${appPubkey} not authorized to delete offer ${offerIdToDelete}`); - return; - } - - await offerRepo.remove(offerToDelete); - this.sendSuccessResponse(requestingPubkey, "Offer deleted successfully", app); - } catch (e) { - console.error("Failed to delete offer", e); - this.sendErrorResponse(requestingPubkey, "Failed to delete offer", app); - } - break; - default: - console.error(`Unknown action: ${action}`); - this.sendErrorResponse(requestingPubkey, `Unknown action: ${action}`, app); - return; - } - } - - private sendSuccessResponse(recipient: string, message: string, app: {publicKey: string, appId: string}) { - const responseEvent = { - kind: 21003, - pubkey: app.publicKey, - created_at: Math.floor(Date.now() / 1000), - content: JSON.stringify({ status: "success", message }), - tags: [['p', recipient]], - }; - this.nostrSend({ type: 'app', appId: app.appId }, { type: 'event', event: responseEvent, encrypt: { toPub: recipient } }); - } - - private sendErrorResponse(recipient: string, message: string, app: {publicKey: string, appId: string}) { - const responseEvent = { - kind: 21003, - pubkey: app.publicKey, - created_at: Math.floor(Date.now() / 1000), - content: JSON.stringify({ status: "error", message }), - tags: [['p', recipient]], - }; - this.nostrSend({ type: 'app', appId: app.appId }, { type: 'event', event: responseEvent, encrypt: { toPub: recipient } }); - } -} \ No newline at end of file diff --git a/src/services/storage/index.ts b/src/services/storage/index.ts index e8f9e771..0bdcc1a2 100644 --- a/src/services/storage/index.ts +++ b/src/services/storage/index.ts @@ -10,6 +10,7 @@ import EventsLogManager from "./eventsLog.js"; import { LiquidityStorage } from "./liquidityStorage.js"; import DebitStorage from "./debitStorage.js" import OfferStorage from "./offerStorage.js" +import { ManagementStorage } from "./managementStorage.js"; import { StorageInterface, TX } from "./db/storageInterface.js"; import { PubLogger } from "../helpers/logger.js" import { TlvStorageFactory } from './tlv/tlvFilesStorageFactory.js'; @@ -36,6 +37,7 @@ export default class { liquidityStorage: LiquidityStorage debitStorage: DebitStorage offerStorage: OfferStorage + managementStorage: ManagementStorage eventsLog: EventsLogManager utils: Utils constructor(settings: StorageSettings, utils: Utils) { @@ -58,6 +60,7 @@ export default class { this.liquidityStorage = new LiquidityStorage(this.dbs) this.debitStorage = new DebitStorage(this.dbs) this.offerStorage = new OfferStorage(this.dbs) + this.managementStorage = new ManagementStorage(this.dbs); try { if (this.settings.dataDir) fs.mkdirSync(this.settings.dataDir) } catch (e) { } /* const executedMetricsMigrations = */ await this.metricsStorage.Connect() /* if (executedMigrations.length > 0) { diff --git a/src/services/storage/managementStorage.ts b/src/services/storage/managementStorage.ts new file mode 100644 index 00000000..53d48af3 --- /dev/null +++ b/src/services/storage/managementStorage.ts @@ -0,0 +1,13 @@ +import { StorageInterface } from "./db/storageInterface.js"; +import { ManagementGrant } from "./entity/ManagementGrant.js"; + +export class ManagementStorage { + private dbs: StorageInterface; + constructor(dbs: StorageInterface) { + this.dbs = dbs; + } + + getGrant(user_id: string, app_pubkey: string) { + return this.dbs.FindOne('ManagementGrant' as any, { where: { user_id, app_pubkey } }); + } +} \ No newline at end of file From 1950bebd74eb2e95b30cb9e35e6aa125521dc51d Mon Sep 17 00:00:00 2001 From: shocknet-justin Date: Sun, 15 Jun 2025 13:47:58 -0400 Subject: [PATCH 06/24] lint --- src/nostrMiddleware.ts | 2 +- src/services/main/index.ts | 7 +++- src/services/main/managementManager.ts | 44 +++++++++++++---------- src/services/storage/managementStorage.ts | 4 +++ 4 files changed, 36 insertions(+), 21 deletions(-) diff --git a/src/nostrMiddleware.ts b/src/nostrMiddleware.ts index aa448295..e91be9f6 100644 --- a/src/nostrMiddleware.ts +++ b/src/nostrMiddleware.ts @@ -40,7 +40,7 @@ export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSett }) let nostr: Nostr; - const managementManager = new ManagementManager((...args: Parameters) => nostr.Send(...args), nostrSettings, mainHandler.storage.managementStorage); + const managementManager = new ManagementManager((...args: Parameters) => nostr.Send(...args), mainHandler.storage); mainHandler.managementManager = managementManager; nostr = new Nostr(nostrSettings, mainHandler.utils, event => { diff --git a/src/services/main/index.ts b/src/services/main/index.ts index 9d7f09bf..46670f8a 100644 --- a/src/services/main/index.ts +++ b/src/services/main/index.ts @@ -26,6 +26,7 @@ import { DebitManager } from "./debitManager.js" import { OfferManager } from "./offerManager.js" import webRTC from "../webRTC/index.js" import { ManagementManager } from "./managementManager.js" +import NostrSubprocess, { LoadNosrtSettingsFromEnv } from "../nostr/index.js" type UserOperationsSub = { id: string @@ -59,8 +60,10 @@ export default class { //webRTC: webRTC nostrSend: NostrSend = () => { getLogger({})("nostr send not initialized yet") } nostrProcessPing: (() => Promise) | null = null - constructor(settings: MainSettings, utils: Utils, unlocker: Unlocker) { + constructor(settings: MainSettings, storage: Storage, adminManager: AdminManager, utils: Utils, unlocker: Unlocker) { this.settings = settings + this.storage = storage + this.adminManager = adminManager this.utils = utils this.unlocker = unlocker const updateProviderBalance = (b: number) => this.storage.liquidityStorage.IncrementTrackedProviderBalance('lnPub', settings.liquiditySettings.liquidityProviderPub, b) @@ -76,6 +79,8 @@ export default class { this.appUserManager = new AppUserManager(this.storage, this.settings, this.applicationManager) this.debitManager = new DebitManager(this.storage, this.lnd, this.applicationManager) this.offerManager = new OfferManager(this.storage, this.lnd, this.applicationManager, this.productManager, this.liquidityManager) + const nostrSettings = LoadNosrtSettingsFromEnv() + this.managementManager = new ManagementManager(this.nostrSend, this.storage) //this.webRTC = new webRTC(this.storage, this.utils) } diff --git a/src/services/main/managementManager.ts b/src/services/main/managementManager.ts index f714ada6..452595e2 100644 --- a/src/services/main/managementManager.ts +++ b/src/services/main/managementManager.ts @@ -2,17 +2,15 @@ import { getRepository } from "typeorm"; import { User } from "../storage/entity/User.js"; import { UserOffer } from "../storage/entity/UserOffer.js"; import { ManagementGrant } from "../storage/entity/ManagementGrant.js"; -import { NostrEvent, NostrSend, NostrSettings } from "../nostr/handler.js"; -import { ManagementStorage } from "../storage/managementStorage.js"; +import { NostrEvent, NostrSend } from "../nostr/handler.js"; +import Storage from "../storage/index.js"; export class ManagementManager { private nostrSend: NostrSend; - private settings: NostrSettings; - private storage: ManagementStorage; + private storage: Storage; - constructor(nostrSend: NostrSend, settings: NostrSettings, storage: ManagementStorage) { + constructor(nostrSend: NostrSend, storage: Storage) { this.nostrSend = nostrSend; - this.settings = settings; this.storage = storage; } @@ -21,23 +19,31 @@ export class ManagementManager { * @param event The raw Nostr event */ public async handleRequest(event: NostrEvent) { - const app = this.settings.apps.find((a: any) => a.appId === event.appId); - if (!app) { - console.error(`App with id ${event.appId} not found in settings`); - return; // Cannot proceed + let app; + try { + app = await this.storage.applicationStorage.GetApplication(event.appId); + } catch { + console.error(`App with id ${event.appId} not found`); + return; } if (!this._validateRequest(event)) { return; } - const grant = await this._checkGrant(event, app.publicKey); - if (!grant) { - this.sendErrorResponse(event.pubkey, "Permission denied.", app); + if (!app.nostr_public_key) { + console.error(`App with id ${event.appId} has no nostr public key configured.`); return; } - await this._performAction(event, app); + const grant = await this._checkGrant(event, app.nostr_public_key); + if (!grant) { + this.sendErrorResponse(event.pubkey, "Permission denied.", { publicKey: app.nostr_public_key, appId: app.app_id }); + return; + } + + const appInfo = { publicKey: app.nostr_public_key, appId: app.app_id }; + await this._performAction(event, appInfo); } private _validateRequest(event: NostrEvent): boolean { @@ -52,7 +58,7 @@ export class ManagementManager { } const userId = userIdTag[1]; - const grant = await this.storage.getGrant(userId, appPubkey); + const grant = await this.storage.managementStorage.getGrant(userId, appPubkey); if (!grant || (grant.expires_at && grant.expires_at.getTime() < Date.now())) { return null; @@ -61,7 +67,7 @@ export class ManagementManager { return grant; } - private async _performAction(event: NostrEvent, app: {publicKey: string, appId: string}) { + private async _performAction(event: NostrEvent, app: { publicKey: string; appId: string }) { const actionTag = event.tags.find((t: string[]) => t[0] === 'a'); if (!actionTag) { console.error("No action specified in event"); @@ -86,7 +92,7 @@ export class ManagementManager { } } - private async _createOffer(event: NostrEvent, app: {publicKey: string, appId: string}) { + private async _createOffer(event: NostrEvent, app: { publicKey: string; appId: string }) { const createDetailsTag = event.tags.find((t: string[]) => t[0] === 'd'); if (!createDetailsTag || !createDetailsTag[1]) { console.error("No details provided for create action"); @@ -111,7 +117,7 @@ export class ManagementManager { } } - private async _updateOffer(event: NostrEvent, app: {publicKey: string, appId: string}) { + private async _updateOffer(event: NostrEvent, app: { publicKey: string; appId: string }) { const updateTags = event.tags.filter((t: string[]) => t[0] === 'd'); if (updateTags.length < 2) { console.error("Insufficient details for update action"); @@ -142,7 +148,7 @@ export class ManagementManager { } } - private async _deleteOffer(event: NostrEvent, app: {publicKey: string, appId: string}) { + private async _deleteOffer(event: NostrEvent, app: { publicKey: string; appId: string }) { const deleteDetailsTag = event.tags.find((t: string[]) => t[0] === 'd'); if (!deleteDetailsTag || !deleteDetailsTag[1]) { console.error("No details provided for delete action"); diff --git a/src/services/storage/managementStorage.ts b/src/services/storage/managementStorage.ts index 53d48af3..3a7e7fd6 100644 --- a/src/services/storage/managementStorage.ts +++ b/src/services/storage/managementStorage.ts @@ -10,4 +10,8 @@ export class ManagementStorage { getGrant(user_id: string, app_pubkey: string) { return this.dbs.FindOne('ManagementGrant' as any, { where: { user_id, app_pubkey } }); } + + async addGrant(user_id: string, app_pubkey: string, expires_at?: Date) { + return this.dbs.CreateAndSave('ManagementGrant' as any, { user_id, app_pubkey, expires_at }); + } } \ No newline at end of file From acb09396ec997f285203e6d4eea4b230a2b87062 Mon Sep 17 00:00:00 2001 From: shocknet-justin Date: Sun, 15 Jun 2025 14:05:03 -0400 Subject: [PATCH 07/24] nostr handler --- src/nostrMiddleware.ts | 7 +++++-- src/services/main/index.ts | 1 - 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/nostrMiddleware.ts b/src/nostrMiddleware.ts index e91be9f6..4ceddf09 100644 --- a/src/nostrMiddleware.ts +++ b/src/nostrMiddleware.ts @@ -40,8 +40,11 @@ export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSett }) let nostr: Nostr; - const managementManager = new ManagementManager((...args: Parameters) => nostr.Send(...args), mainHandler.storage); - mainHandler.managementManager = managementManager; + if (!mainHandler.managementManager) { + throw new Error("management manager not initialized on main handler") + } + + const managementManager = mainHandler.managementManager; nostr = new Nostr(nostrSettings, mainHandler.utils, event => { let j: NostrRequest diff --git a/src/services/main/index.ts b/src/services/main/index.ts index 46670f8a..18e898b8 100644 --- a/src/services/main/index.ts +++ b/src/services/main/index.ts @@ -79,7 +79,6 @@ export default class { this.appUserManager = new AppUserManager(this.storage, this.settings, this.applicationManager) this.debitManager = new DebitManager(this.storage, this.lnd, this.applicationManager) this.offerManager = new OfferManager(this.storage, this.lnd, this.applicationManager, this.productManager, this.liquidityManager) - const nostrSettings = LoadNosrtSettingsFromEnv() this.managementManager = new ManagementManager(this.nostrSend, this.storage) //this.webRTC = new webRTC(this.storage, this.utils) } From 668a5bbac523835d9b9b4ba10da43086a3f1ee8a Mon Sep 17 00:00:00 2001 From: boufni95 Date: Mon, 30 Jun 2025 17:47:21 +0000 Subject: [PATCH 08/24] nmanage backend flow --- package-lock.json | 8 +- package.json | 2 +- src/e2e.ts | 3 +- src/index.ts | 8 +- src/nostrMiddleware.ts | 16 +- src/services/main/appUserManager.ts | 3 +- src/services/main/applicationManager.ts | 5 +- src/services/main/index.ts | 10 +- src/services/main/managementManager.ts | 375 ++++++++++-------- src/services/main/offerManager.ts | 11 +- src/services/main/settings.ts | 5 +- src/services/nostr/handler.ts | 49 ++- src/services/nostr/index.ts | 13 +- .../storage/entity/ManagementGrant.ts | 25 +- src/services/storage/entity/UserOffer.ts | 4 +- src/services/storage/managementStorage.ts | 8 +- src/services/storage/offerStorage.ts | 5 + 17 files changed, 303 insertions(+), 247 deletions(-) diff --git a/package-lock.json b/package-lock.json index 6042c818..8d642916 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,7 +13,7 @@ "@protobuf-ts/grpc-transport": "^2.9.4", "@protobuf-ts/plugin": "^2.5.0", "@protobuf-ts/runtime": "^2.5.0", - "@shocknet/clink-sdk": "^1.0.4", + "@shocknet/clink-sdk": "^1.1.2", "@stablelib/xchacha20": "^1.0.1", "@types/express": "^4.17.21", "@types/node": "^17.0.31", @@ -591,9 +591,9 @@ } }, "node_modules/@shocknet/clink-sdk": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@shocknet/clink-sdk/-/clink-sdk-1.0.4.tgz", - "integrity": "sha512-ekkfJpP+YPry4/5+V+3JPx9zOVEjCDOWW7AHzfOLyVGnLuIR6jEBjDkg7avM2f3BVvFKSl4l0mkS9ImK9lX0eQ==", + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@shocknet/clink-sdk/-/clink-sdk-1.1.2.tgz", + "integrity": "sha512-nICsXlLZRIs6E+wy3PfQccIidmQ/D7uSHfHfqrJzNJFOUH2+XGDkApB9TQU1eTrNgD/BHxm9tSZkEmG0it7I3w==", "license": "ISC", "dependencies": { "@noble/hashes": "^1.8.0", diff --git a/package.json b/package.json index 36412acd..63ef6c1e 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,7 @@ "@protobuf-ts/grpc-transport": "^2.9.4", "@protobuf-ts/plugin": "^2.5.0", "@protobuf-ts/runtime": "^2.5.0", - "@shocknet/clink-sdk": "^1.0.4", + "@shocknet/clink-sdk": "^1.1.2", "@stablelib/xchacha20": "^1.0.1", "@types/express": "^4.17.21", "@types/node": "^17.0.31", diff --git a/src/e2e.ts b/src/e2e.ts index 886202be..bcb16e3d 100644 --- a/src/e2e.ts +++ b/src/e2e.ts @@ -2,7 +2,6 @@ import 'dotenv/config' import NewServer from '../proto/autogenerated/ts/express_server.js' import GetServerMethods from './services/serverMethods/index.js' import serverOptions from './auth.js'; -import { LoadNosrtSettingsFromEnv } from './services/nostr/index.js' import nostrMiddleware from './nostrMiddleware.js' import { getLogger } from './services/helpers/logger.js'; import { initMainHandler } from './services/main/init.js'; @@ -22,7 +21,7 @@ const start = async () => { const { apps, mainHandler, liquidityProviderInfo, wizard, adminManager } = keepOn const serverMethods = GetServerMethods(mainHandler) - const nostrSettings = LoadNosrtSettingsFromEnv() + const nostrSettings = mainSettings.nostrRelaySettings log("initializing nostr middleware") const { Send } = nostrMiddleware(serverMethods, mainHandler, { ...nostrSettings, apps, clients: [liquidityProviderInfo] }, diff --git a/src/index.ts b/src/index.ts index 49ffa1f4..1a56397d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,7 +2,6 @@ import 'dotenv/config' import NewServer from '../proto/autogenerated/ts/express_server.js' import GetServerMethods from './services/serverMethods/index.js' import serverOptions from './auth.js'; -import { LoadNosrtSettingsFromEnv } from './services/nostr/index.js' import nostrMiddleware from './nostrMiddleware.js' import { getLogger } from './services/helpers/logger.js'; import { initMainHandler } from './services/main/init.js'; @@ -22,10 +21,9 @@ const start = async () => { const { apps, mainHandler, liquidityProviderInfo, wizard, adminManager } = keepOn const serverMethods = GetServerMethods(mainHandler) - const nostrSettings = LoadNosrtSettingsFromEnv() log("initializing nostr middleware") const { Send, Stop, Ping } = nostrMiddleware(serverMethods, mainHandler, - { ...nostrSettings, apps, clients: [liquidityProviderInfo] }, + { ...mainSettings.nostrRelaySettings, apps, clients: [liquidityProviderInfo] }, (e, p) => mainHandler.liquidityProvider.onEvent(e, p) ) exitHandler(() => { Stop(); mainHandler.Stop() }) @@ -33,9 +31,9 @@ const start = async () => { mainHandler.attachNostrSend(Send) mainHandler.attachNostrProcessPing(Ping) mainHandler.StartBeacons() - const appNprofile = nprofileEncode({ pubkey: liquidityProviderInfo.publicKey, relays: nostrSettings.relays }) + const appNprofile = nprofileEncode({ pubkey: liquidityProviderInfo.publicKey, relays: mainSettings.nostrRelaySettings.relays }) if (wizard) { - wizard.AddConnectInfo(appNprofile, nostrSettings.relays) + wizard.AddConnectInfo(appNprofile, mainSettings.nostrRelaySettings.relays) } adminManager.setAppNprofile(appNprofile) const Server = NewServer(serverMethods, serverOptions(mainHandler)) diff --git a/src/nostrMiddleware.ts b/src/nostrMiddleware.ts index 4ceddf09..3c6d4434 100644 --- a/src/nostrMiddleware.ts +++ b/src/nostrMiddleware.ts @@ -5,7 +5,7 @@ import * as Types from '../proto/autogenerated/ts/types.js' import NewNostrTransport, { NostrRequest } from '../proto/autogenerated/ts/nostr_transport.js'; import { ERROR, getLogger } from "./services/helpers/logger.js"; import { NdebitData, NofferData } from "@shocknet/clink-sdk"; -import { ManagementManager } from "./services/main/managementManager.js"; +import { NmanageRequest } from "./services/main/managementManager.js"; export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSettings: NostrSettings, onClientEvent: (e: { requestId: string }, fromPub: string) => void): { Stop: () => void, Send: NostrSend, Ping: () => Promise } => { const log = getLogger({}) @@ -39,14 +39,7 @@ export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSett logger: { log: console.log, error: err => log(ERROR, err) }, }) - let nostr: Nostr; - if (!mainHandler.managementManager) { - throw new Error("management manager not initialized on main handler") - } - - const managementManager = mainHandler.managementManager; - - nostr = new Nostr(nostrSettings, mainHandler.utils, event => { + const nostr = new Nostr(nostrSettings, mainHandler.utils, event => { let j: NostrRequest try { j = JSON.parse(event.content) @@ -64,7 +57,8 @@ export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSett mainHandler.debitManager.handleNip68Debit(debitReq, event) return } else if (event.kind === 21003) { - managementManager.handleRequest(event); + const nmanageReq = j as NmanageRequest + mainHandler.managementManager.handleRequest(nmanageReq, event); return; } if (!j.rpcName) { @@ -80,7 +74,7 @@ export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSett }, event.startAtNano, event.startAtMs) }) - return { Stop: () => nostr.Stop, Send: (...args: Parameters) => nostr.Send(...args), Ping: () => nostr.Ping() } + return { Stop: () => nostr.Stop, Send: (...args) => nostr.Send(...args), Ping: () => nostr.Ping() } } diff --git a/src/services/main/appUserManager.ts b/src/services/main/appUserManager.ts index 39b2ba4b..087197fb 100644 --- a/src/services/main/appUserManager.ts +++ b/src/services/main/appUserManager.ts @@ -4,7 +4,6 @@ import * as Types from '../../../proto/autogenerated/ts/types.js' import { MainSettings } from './settings.js' import ApplicationManager from './applicationManager.js' -import { LoadNosrtSettingsFromEnv } from '../nostr/index.js' import { OfferPriceType, ndebitEncode, nofferEncode } from '@shocknet/clink-sdk' export default class { @@ -66,7 +65,7 @@ export default class { if (!appUser) { throw new Error(`app user ${ctx.user_id} not found`) // TODO: fix logs doxing } - const nostrSettings = LoadNosrtSettingsFromEnv() + const nostrSettings = this.settings.nostrRelaySettings return { userId: ctx.user_id, balance: user.balance_sats, diff --git a/src/services/main/applicationManager.ts b/src/services/main/applicationManager.ts index edab50a2..df1f035a 100644 --- a/src/services/main/applicationManager.ts +++ b/src/services/main/applicationManager.ts @@ -8,7 +8,6 @@ import { ApplicationUser } from '../storage/entity/ApplicationUser.js' import { PubLogger, getLogger } from '../helpers/logger.js' import crypto from 'crypto' import { Application } from '../storage/entity/Application.js' -import { LoadNosrtSettingsFromEnv } from '../nostr/index.js' import { ZapInfo } from '../storage/entity/UserReceivingInvoice.js' import { nofferEncode, ndebitEncode, OfferPriceType } from '@shocknet/clink-sdk' const TOKEN_EXPIRY_TIME = 2 * 60 * 1000 // 2 minutes, in milliseconds @@ -151,7 +150,7 @@ export default class { u = user if (created) log(u.identifier, u.user.user_id, "user created") } - const nostrSettings = LoadNosrtSettingsFromEnv() + const nostrSettings = this.settings.nostrRelaySettings return { identifier: u.identifier, info: { @@ -205,7 +204,7 @@ export default class { const app = await this.storage.applicationStorage.GetApplication(appId) const user = await this.storage.applicationStorage.GetApplicationUser(app, req.user_identifier) const max = this.paymentManager.GetMaxPayableInvoice(user.user.balance_sats, true) - const nostrSettings = LoadNosrtSettingsFromEnv() + const nostrSettings = this.settings.nostrRelaySettings return { max_withdrawable: max, identifier: req.user_identifier, info: { userId: user.user.user_id, balance: user.user.balance_sats, diff --git a/src/services/main/index.ts b/src/services/main/index.ts index 18e898b8..22f6c31a 100644 --- a/src/services/main/index.ts +++ b/src/services/main/index.ts @@ -26,7 +26,6 @@ import { DebitManager } from "./debitManager.js" import { OfferManager } from "./offerManager.js" import webRTC from "../webRTC/index.js" import { ManagementManager } from "./managementManager.js" -import NostrSubprocess, { LoadNosrtSettingsFromEnv } from "../nostr/index.js" type UserOperationsSub = { id: string @@ -53,7 +52,7 @@ export default class { liquidityProvider: LiquidityProvider debitManager: DebitManager offerManager: OfferManager - managementManager?: ManagementManager + managementManager: ManagementManager utils: Utils rugPullTracker: RugPullTracker unlocker: Unlocker @@ -79,7 +78,7 @@ export default class { this.appUserManager = new AppUserManager(this.storage, this.settings, this.applicationManager) this.debitManager = new DebitManager(this.storage, this.lnd, this.applicationManager) this.offerManager = new OfferManager(this.storage, this.lnd, this.applicationManager, this.productManager, this.liquidityManager) - this.managementManager = new ManagementManager(this.nostrSend, this.storage) + this.managementManager = new ManagementManager(this.storage, this.offerManager) //this.webRTC = new webRTC(this.storage, this.utils) } @@ -102,6 +101,7 @@ export default class { this.liquidityProvider.attachNostrSend(f) this.debitManager.attachNostrSend(f) this.offerManager.attachNostrSend(f) + this.managementManager.attachNostrSend(f) this.utils.attachNostrSend(f) //this.webRTC.attachNostrSend(f) } @@ -344,10 +344,6 @@ export default class { log({ unsigned: event }) this.nostrSend({ type: 'app', appId: invoice.linkedApplication.app_id }, { type: 'event', event }, zapInfo.relays || undefined) } - - async Start() { - // ... existing code ... - } } diff --git a/src/services/main/managementManager.ts b/src/services/main/managementManager.ts index 452595e2..26bf6b4d 100644 --- a/src/services/main/managementManager.ts +++ b/src/services/main/managementManager.ts @@ -4,198 +4,259 @@ import { UserOffer } from "../storage/entity/UserOffer.js"; import { ManagementGrant } from "../storage/entity/ManagementGrant.js"; import { NostrEvent, NostrSend } from "../nostr/handler.js"; import Storage from "../storage/index.js"; +import { OfferManager } from "./offerManager.js"; +import * as Types from "../../../proto/autogenerated/ts/types.js"; +import { MainSettings } from "./settings.js"; +import { nofferEncode, OfferPointer, OfferPriceType, NmanageRequest, NmanageResponse, NmanageCreateOffer, NmanageUpdateOffer, NmanageDeleteOffer, NmanageGetOffer, NmanageListOffers, OfferData, OfferFields } from "@shocknet/clink-sdk"; +import { UnsignedEvent } from "nostr-tools"; +type Result = { success: true, result: T } | { success: false, error: string, code: number } export class ManagementManager { private nostrSend: NostrSend; private storage: Storage; + private settings: MainSettings; - constructor(nostrSend: NostrSend, storage: Storage) { - this.nostrSend = nostrSend; + constructor(storage: Storage, settings: MainSettings) { this.storage = storage; + this.settings = settings; } - /** - * Handles an incoming CLINK Manage request - * @param event The raw Nostr event - */ - public async handleRequest(event: NostrEvent) { - let app; + attachNostrSend(f: NostrSend) { + this.nostrSend = f + } + + public async handleRequest(nmanageReq: NmanageRequest, event: NostrEvent): Promise { try { - app = await this.storage.applicationStorage.GetApplication(event.appId); - } catch { - console.error(`App with id ${event.appId} not found`); - return; + const r = await this.doNmanage(nmanageReq, event) + let e: UnsignedEvent + if (!r.success) { + e = newNmanageResponse(JSON.stringify({ code: r.code, error: codeToMessage(r.code) }), event) + } else { + e = newNmanageResponse(JSON.stringify(r.result), event) + } + this.nostrSend({ type: 'app', appId: event.appId }, { type: 'event', event: e, encrypt: { toPub: event.pub } }) + } catch (err) { + const e = newNmanageResponse(JSON.stringify({ code: 2, error: codeToMessage(2) }), event) + this.nostrSend({ type: 'app', appId: event.appId }, { type: 'event', event: e, encrypt: { toPub: event.pub } }) } - - if (!this._validateRequest(event)) { - return; - } - - if (!app.nostr_public_key) { - console.error(`App with id ${event.appId} has no nostr public key configured.`); - return; - } - - const grant = await this._checkGrant(event, app.nostr_public_key); - if (!grant) { - this.sendErrorResponse(event.pubkey, "Permission denied.", { publicKey: app.nostr_public_key, appId: app.app_id }); - return; - } - - const appInfo = { publicKey: app.nostr_public_key, appId: app.app_id }; - await this._performAction(event, appInfo); } - private _validateRequest(event: NostrEvent): boolean { - // TODO: NIP-44 validation or similar - return true; - } - - private async _checkGrant(event: NostrEvent, appPubkey: string): Promise { - const userIdTag = event.tags.find((t: string[]) => t[0] === 'p'); - if (!userIdTag) { - return null; - } - const userId = userIdTag[1]; - - const grant = await this.storage.managementStorage.getGrant(userId, appPubkey); - - if (!grant || (grant.expires_at && grant.expires_at.getTime() < Date.now())) { - return null; - } - - return grant; - } - - private async _performAction(event: NostrEvent, app: { publicKey: string; appId: string }) { - const actionTag = event.tags.find((t: string[]) => t[0] === 'a'); - if (!actionTag) { - console.error("No action specified in event"); - return; - } - - const action = actionTag[1]; - + private async doNmanage(nmanageReq: NmanageRequest, event: NostrEvent): Promise> { + const action = nmanageReq.action switch (action) { case "create": - await this._createOffer(event, app); - break; + const createResult = await this.createOffer(nmanageReq) + return this.getNmanageResponse(event.appId, createResult) case "update": - await this._updateOffer(event, app); - break; + const updateResult = await this.updateOffer(nmanageReq, event.pub); + return this.getNmanageResponse(event.appId, updateResult) case "delete": - await this._deleteOffer(event, app); - break; + const deleteResult = await this.deleteOffer(nmanageReq, event.pub); + return this.getNmanageResponse(event.appId, deleteResult) + case "get": + const getResult = await this.getOffer(nmanageReq, event.pub); + return this.getNmanageResponse(event.appId, getResult) + case "list": + const listResult = await this.listOffers(nmanageReq, event.pub); + return this.getNmanageResponse(event.appId, listResult) default: - console.error(`Unknown action: ${action}`); - this.sendErrorResponse(event.pubkey, `Unknown action: ${action}`, app); + return { success: false, error: `Unknown action: ${action}`, code: 1 } } } - private async _createOffer(event: NostrEvent, app: { publicKey: string; appId: string }) { - const createDetailsTag = event.tags.find((t: string[]) => t[0] === 'd'); - if (!createDetailsTag || !createDetailsTag[1]) { - console.error("No details provided for create action"); - return; + private getOfferData(offer: UserOffer, appPub: string): OfferData { + const pointer: OfferPointer = { + offer: offer.offer_id, + pubkey: appPub, + relay: this.settings.nostrRelaySettings.relays[0], + priceType: offer.price_sats > 0 ? OfferPriceType.Fixed : OfferPriceType.Spontaneous, + price: offer.price_sats, } - - const userId = event.tags.find((t: string[]) => t[0] === 'p')![1]; - - try { - const offerData = JSON.parse(createDetailsTag[1]); - const offerRepo = getRepository(UserOffer); - const newOffer = offerRepo.create({ - ...offerData, - user_id: userId, - managing_app_pubkey: app.publicKey - }); - await offerRepo.save(newOffer); - this.sendSuccessResponse(event.pubkey, "Offer created successfully", app); - } catch (e) { - console.error("Failed to parse or save offer data", e); - this.sendErrorResponse(event.pubkey, "Failed to create offer", app); + return { + id: offer.offer_id, + label: offer.label, + price_sats: offer.price_sats, + callback_url: offer.callback_url, + payer_data: Object.keys(offer.expected_data || {}), + noffer: nofferEncode(pointer), } } - private async _updateOffer(event: NostrEvent, app: { publicKey: string; appId: string }) { - const updateTags = event.tags.filter((t: string[]) => t[0] === 'd'); - if (updateTags.length < 2) { - console.error("Insufficient details for update action"); - return; + private async getNmanageResponse(appId: string, result: Result): Promise> { + if (!result.success) { + return result } - const offerIdToUpdate = updateTags[0][1]; - const updateData = JSON.parse(updateTags[1][1]); - const offerRepo = getRepository(UserOffer); - - try { - const existingOffer = await offerRepo.findOne({where: { offer_id: offerIdToUpdate }}); - if (!existingOffer) { - console.error(`Offer ${offerIdToUpdate} not found`); - return; + const args = result.result + const app = await this.storage.applicationStorage.GetApplication(appId) + if (args && Array.isArray(args)) { + return { + success: true, result: { + res: 'ok', resource: 'offer', details: args.map(offer => this.getOfferData(offer, app.nostr_public_key!)) + } } - - if (existingOffer.managing_app_pubkey !== app.publicKey) { - console.error(`App ${app.publicKey} not authorized to update offer ${offerIdToUpdate}`); - return; + } + if (!args) { + return { success: true, result: { res: 'ok', resource: 'offer' } } + } + return { + success: true, result: { + res: 'ok', resource: 'offer', details: this.getOfferData(args, app.nostr_public_key!) } - - offerRepo.merge(existingOffer, updateData); - await offerRepo.save(existingOffer); - this.sendSuccessResponse(event.pubkey, "Offer updated successfully", app); - } catch (e) { - console.error("Failed to update offer data", e); - this.sendErrorResponse(event.pubkey, "Failed to update offer", app); } } - private async _deleteOffer(event: NostrEvent, app: { publicKey: string; appId: string }) { - const deleteDetailsTag = event.tags.find((t: string[]) => t[0] === 'd'); - if (!deleteDetailsTag || !deleteDetailsTag[1]) { - console.error("No details provided for delete action"); - return; + private async getOffer(nmanageReq: NmanageGetOffer, requestorPub: string): Promise> { + const offer = await this.validateOfferAccess(nmanageReq.offer.id, requestorPub) + if (!offer.success) { + return offer } - const offerIdToDelete = deleteDetailsTag[1]; - const offerRepo = getRepository(UserOffer); + return { success: true, result: offer.result } + } - try { - const offerToDelete = await offerRepo.findOne({where: { offer_id: offerIdToDelete }}); - if (!offerToDelete) { - console.error(`Offer ${offerIdToDelete} not found`); - return; - } - - if (offerToDelete.managing_app_pubkey !== app.publicKey) { - console.error(`App ${app.publicKey} not authorized to delete offer ${offerIdToDelete}`); - return; - } - - await offerRepo.remove(offerToDelete); - this.sendSuccessResponse(event.pubkey, "Offer deleted successfully", app); - } catch (e) { - console.error("Failed to delete offer", e); - this.sendErrorResponse(event.pubkey, "Failed to delete offer", app); + private async listOffers(nmanageReq: NmanageListOffers, requestorPub: string): Promise> { + const appUserId = nmanageReq.pointer + if (!appUserId) { + return { success: false, error: 'No pointer provided', code: 1 } } + const grantResult = await this.validateGrantAccess(appUserId, requestorPub) + if (!grantResult.success) { + return grantResult + } + const offers = await this.storage.offerStorage.getManagedUserOffers(appUserId, requestorPub) + return { success: true, result: offers } } - private sendSuccessResponse(recipient: string, message: string, app: {publicKey: string, appId: string}) { - const responseEvent = { - kind: 21003, - pubkey: app.publicKey, - created_at: Math.floor(Date.now() / 1000), - content: JSON.stringify({ status: "success", message }), - tags: [['p', recipient]], - }; - this.nostrSend({ type: 'app', appId: app.appId }, { type: 'event', event: responseEvent, encrypt: { toPub: recipient } }); + private validateOfferFields(fields: OfferFields): Result { + if (!fields.label || typeof fields.label !== 'string') { + return { success: false, error: 'Label is required', code: 1 } + } + if (fields.price_sats && typeof fields.price_sats !== 'number') { + return { success: false, error: 'Price must be a number', code: 1 } + } + if (fields.callback_url && typeof fields.callback_url !== 'string') { + return { success: false, error: 'Callback URL must be a string', code: 1 } + } + if (fields.payer_data && !Array.isArray(fields.payer_data)) { + return { success: false, error: 'Payer data must be an array', code: 1 } + } + + return { success: true, result: undefined } } - private sendErrorResponse(recipient: string, message: string, app: {publicKey: string, appId: string}) { - const responseEvent = { - kind: 21003, - pubkey: app.publicKey, - created_at: Math.floor(Date.now() / 1000), - content: JSON.stringify({ status: "error", message }), - tags: [['p', recipient]], - }; - this.nostrSend({ type: 'app', appId: app.appId }, { type: 'event', event: responseEvent, encrypt: { toPub: recipient } }); + private async createOffer(nmanageReq: NmanageCreateOffer): Promise> { + const appUserId = nmanageReq.pointer + if (!appUserId) { + return { success: false, error: 'No pointer provided', code: 1 } + } + const grantResult = await this.validateGrantAccess(appUserId, appUserId) + if (!grantResult.success) { + return grantResult + } + const validateResult = this.validateOfferFields(nmanageReq.offer.fields) + if (!validateResult.success) { + return validateResult + } + const dataMap: Record = {} + nmanageReq.offer.fields.payer_data.forEach(data => { + dataMap[data] = Types.OfferDataType.DATA_STRING + }) + const offer = await this.storage.offerStorage.AddUserOffer(appUserId, { + label: nmanageReq.offer.fields.label, + callback_url: nmanageReq.offer.fields.callback_url, + price_sats: nmanageReq.offer.fields.price_sats, + expected_data: dataMap, + }) + return { success: true, result: offer } } -} \ No newline at end of file + + private async validateGrantAccess(appUserId: string, requestorPub: string): Promise> { + const grant = await this.storage.managementStorage.getGrant(appUserId, requestorPub) + + if (!grant) { + // TODO request from user + return { success: false, error: 'No grant found', code: 1 } + } + + if (grant.expires_at_unix < Date.now()) { + return { success: false, error: 'Grant expired', code: 3 } + } + return { success: true, result: undefined } + } + + private async validateOfferAccess(offerId: string, requestorPub: string): Promise> { + const offer = await this.storage.offerStorage.GetOffer(offerId) + if (!offer) { + return { success: false, error: 'Offer not found', code: 1 } + } + if (offer.management_pubkey !== requestorPub) { + return { success: false, error: 'App not authorized to update offer', code: 1 } + } + const grantResult = await this.validateGrantAccess(offer.app_user_id, requestorPub) + if (!grantResult.success) { + return grantResult + } + return { success: true, result: offer } + } + + private async updateOffer(nmanageReq: NmanageUpdateOffer, requestorPub: string): Promise> { + const offer = await this.validateOfferAccess(nmanageReq.offer.id, requestorPub) + if (!offer.success) { + return offer + } + const validateResult = this.validateOfferFields(nmanageReq.offer.fields) + if (!validateResult.success) { + return validateResult + } + const dataMap: Record = {} + for (const data of nmanageReq.offer.fields.payer_data || []) { + if (typeof data !== 'string') { + return { success: false, error: 'Payer data must be a string', code: 1 } + } + dataMap[data] = Types.OfferDataType.DATA_STRING + } + await this.storage.offerStorage.UpdateUserOffer(offer.result.app_user_id, nmanageReq.offer.id, { + label: nmanageReq.offer.fields.label, + callback_url: nmanageReq.offer.fields.callback_url, + price_sats: nmanageReq.offer.fields.price_sats, + expected_data: dataMap, + }) + const updatedOffer = await this.storage.offerStorage.GetOffer(nmanageReq.offer.id) + if (!updatedOffer) { + return { success: false, error: 'Offer not found', code: 2 } + } + return { success: true, result: updatedOffer } + } + + private async deleteOffer(nmanageReq: NmanageDeleteOffer, requestorPub: string): Promise> { + const offerResult = await this.validateOfferAccess(nmanageReq.offer.id, requestorPub) + if (!offerResult.success) { + return offerResult + } + await this.storage.offerStorage.DeleteUserOffer(offerResult.result.app_user_id, offerResult.result.offer_id) + return { success: true, result: undefined } + } +} + +const newNmanageResponse = (content: string, event: NostrEvent): UnsignedEvent => { + return { + content, + created_at: Math.floor(Date.now() / 1000), + kind: 21003, + pubkey: "", + tags: [ + ['p', event.pub], + ['e', event.id], + ], + } +} +const codeToMessage = (code: number, reason = "") => { + switch (code) { + case 1: return 'Request Denied' + case 2: return 'Temporary Failure: ' + reason + case 3: return 'Expired Request' + case 4: return 'Rate Limited' + case 5: return 'Invalid Field or Value' + case 6: return 'Invalid Request: ' + reason + default: throw new Error("unknown error code" + code) + } +} \ No newline at end of file diff --git a/src/services/main/offerManager.ts b/src/services/main/offerManager.ts index 26e35816..3aaae490 100644 --- a/src/services/main/offerManager.ts +++ b/src/services/main/offerManager.ts @@ -7,9 +7,9 @@ import { ERROR, getLogger } from "../helpers/logger.js"; import { NostrEvent, NostrSend, SendData, SendInitiator } from '../nostr/handler.js'; import { UnsignedEvent } from 'nostr-tools'; import { UserOffer } from '../storage/entity/UserOffer.js'; -import { LoadNosrtSettingsFromEnv } from '../nostr/index.js'; import { LiquidityManager } from "./liquidityManager.js" import { NofferData, OfferPriceType, nofferEncode } from '@shocknet/clink-sdk'; +import { MainSettings } from "./settings.js"; const mapToOfferConfig = (appUserId: string, offer: UserOffer, { pubkey, relay }: { pubkey: string, relay: string }): Types.OfferConfig => { if (offer.expected_data) { @@ -38,15 +38,16 @@ export class OfferManager { _nostrSend: NostrSend | null = null - + settings: MainSettings applicationManager: ApplicationManager productManager: ProductManager storage: Storage lnd: LND liquidityManager: LiquidityManager logger = getLogger({ component: 'DebitManager' }) - constructor(storage: Storage, lnd: LND, applicationManager: ApplicationManager, productManager: ProductManager, liquidityManager: LiquidityManager) { + constructor(storage: Storage, settings: MainSettings, lnd: LND, applicationManager: ApplicationManager, productManager: ProductManager, liquidityManager: LiquidityManager) { this.storage = storage + this.settings = settings this.lnd = lnd this.applicationManager = applicationManager this.productManager = productManager @@ -113,7 +114,7 @@ export class OfferManager { if (!offer) { throw new Error("Offer not found") } - const nostrSettings = LoadNosrtSettingsFromEnv() + const nostrSettings = this.settings.nostrRelaySettings return mapToOfferConfig(ctx.app_user_id, offer, { pubkey: app.npub, relay: nostrSettings.relays[0] }) } @@ -131,7 +132,7 @@ export class OfferManager { if (toAppend) { offers.push(toAppend) } - const nostrSettings = LoadNosrtSettingsFromEnv() + const nostrSettings = this.settings.nostrRelaySettings return { offers: offers.map(o => mapToOfferConfig(ctx.app_user_id, o, { pubkey: app.npub, relay: nostrSettings.relays[0] })) } diff --git a/src/services/main/settings.ts b/src/services/main/settings.ts index fe1d6b7d..5c831c75 100644 --- a/src/services/main/settings.ts +++ b/src/services/main/settings.ts @@ -7,12 +7,14 @@ import { getLogger } from '../helpers/logger.js' import fs from 'fs' import crypto from 'crypto'; import { LiquiditySettings, LoadLiquiditySettingsFromEnv } from './liquidityManager.js' +import { LoadNosrtRelaySettingsFromEnv, NostrRelaySettings } from '../nostr/handler.js' export type MainSettings = { storageSettings: StorageSettings, lndSettings: LndSettings, watchDogSettings: WatchdogSettings, liquiditySettings: LiquiditySettings, + nostrRelaySettings: NostrRelaySettings, jwtSecret: string walletPasswordPath: string walletSecretPath: string @@ -49,12 +51,13 @@ export type TestSettings = MainSettings & { lndSettings: { otherNode: NodeSettin export const LoadMainSettingsFromEnv = (): MainSettings => { const storageSettings = LoadStorageSettingsFromEnv() const outgoingAppUserInvoiceFeeBps = EnvCanBeInteger("OUTGOING_INVOICE_FEE_USER_BPS", 0) - + const nostrRelaySettings = LoadNosrtRelaySettingsFromEnv() return { watchDogSettings: LoadWatchdogSettingsFromEnv(), lndSettings: LoadLndSettingsFromEnv(), storageSettings: storageSettings, liquiditySettings: LoadLiquiditySettingsFromEnv(), + nostrRelaySettings: nostrRelaySettings, jwtSecret: loadJwtSecret(storageSettings.dataDir), walletSecretPath: process.env.WALLET_SECRET_PATH || getDataPath(storageSettings.dataDir, ".wallet_secret"), walletPasswordPath: process.env.WALLET_PASSWORD_PATH || getDataPath(storageSettings.dataDir, ".wallet_password"), diff --git a/src/services/nostr/handler.ts b/src/services/nostr/handler.ts index ce064bc7..553c8d6f 100644 --- a/src/services/nostr/handler.ts +++ b/src/services/nostr/handler.ts @@ -7,6 +7,7 @@ import { ERROR, getLogger } from '../helpers/logger.js' import { nip19 } from 'nostr-tools' import { encrypt as encryptV1, decrypt as decryptV1, getSharedSecret as getConversationKeyV1 } from './nip44v1.js' import { ProcessMetrics, ProcessMetricsCollector } from '../storage/tlv/processMetricsCollector.js' +import { EnvCanBeInteger, } from '../helpers/envParser.js' const { nprofileEncode } = nip19 const { v2 } = nip44 const { encrypt: encryptV2, decrypt: decryptV2, utils } = v2 @@ -26,16 +27,34 @@ export type NostrSettings = { clients: ClientInfo[] maxEventContentLength: number } -export type NostrEvent = Event & { - /** Identifier of the application as defined in NostrSettings.apps */ - appId: string; - /** High-resolution timer capture when processing began (BigInt serialized as string to keep JSON friendly) */ - startAtNano: string; - /** wall-clock millis when processing began */ - startAtMs: number; - /** Convenience duplicate of the sender pubkey (e.pubkey) kept for backwards-compat */ - pub: string; -}; + +export type NostrRelaySettings = { + relays: string[], + maxEventContentLength: number +} + +const getEnvOrDefault = (name: string, defaultValue: string): string => { + return process.env[name] || defaultValue; +} + +export const LoadNosrtRelaySettingsFromEnv = (test = false): NostrRelaySettings => { + const relaysEnv = getEnvOrDefault("NOSTR_RELAYS", "wss://relay.lightning.pub"); + const maxEventContentLength = EnvCanBeInteger("NOSTR_MAX_EVENT_CONTENT_LENGTH", 40000) + return { + relays: relaysEnv.split(' '), + maxEventContentLength + } +} + +export type NostrEvent = { + id: string + pub: string + content: string + appId: string + startAtNano: string + startAtMs: number + kind: number +} type SettingsRequest = { type: 'settings' @@ -217,15 +236,7 @@ export default class Handler { return } - const nostrEvent: NostrEvent = { - ...e, - content, - appId: app.appId, - startAtNano, - startAtMs, - pub: e.pubkey, - } - this.eventCallback(nostrEvent) + this.eventCallback({ id: eventId, content, pub: e.pubkey, appId: app.appId, startAtNano, startAtMs, kind: e.kind }) } async Send(initiator: SendInitiator, data: SendData, relays?: string[]) { diff --git a/src/services/nostr/index.ts b/src/services/nostr/index.ts index 6e6a6e6b..288478ec 100644 --- a/src/services/nostr/index.ts +++ b/src/services/nostr/index.ts @@ -4,18 +4,9 @@ import { NostrSettings, NostrEvent, ChildProcessRequest, ChildProcessResponse, S import { Utils } from '../helpers/utilsWrapper.js' type EventCallback = (event: NostrEvent) => void -const getEnvOrDefault = (name: string, defaultValue: string): string => { - return process.env[name] || defaultValue; -} -export const LoadNosrtSettingsFromEnv = (test = false) => { - const relaysEnv = getEnvOrDefault("NOSTR_RELAYS", "wss://relay.lightning.pub"); - const maxEventContentLength = EnvCanBeInteger("NOSTR_MAX_EVENT_CONTENT_LENGTH", 40000) - return { - relays: relaysEnv.split(' '), - maxEventContentLength - } -} + + export default class NostrSubprocess { settings: NostrSettings diff --git a/src/services/storage/entity/ManagementGrant.ts b/src/services/storage/entity/ManagementGrant.ts index 16a3499f..978cc236 100644 --- a/src/services/storage/entity/ManagementGrant.ts +++ b/src/services/storage/entity/ManagementGrant.ts @@ -1,24 +1,23 @@ -import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, ManyToOne, JoinColumn } from "typeorm"; +import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, ManyToOne, JoinColumn, UpdateDateColumn } from "typeorm"; import { User } from "./User"; @Entity("management_grants") export class ManagementGrant { - @PrimaryGeneratedColumn("uuid") - id: string; + @PrimaryGeneratedColumn() + serial_id: number @Column() - user_id: string; - - @ManyToOne(() => User) - @JoinColumn({ name: "user_id", referencedColumnName: "user_id" }) - user: User; + app_user_id: string @Column() app_pubkey: string; - @CreateDateColumn() - created_at: Date; + @Column() + expires_at_unix: number - @Column({ type: 'timestamp', nullable: true }) - expires_at: Date; -} \ No newline at end of file + @CreateDateColumn() + created_at: Date + + @UpdateDateColumn() + updated_at: Date +} \ No newline at end of file diff --git a/src/services/storage/entity/UserOffer.ts b/src/services/storage/entity/UserOffer.ts index 833e6ca9..691a529b 100644 --- a/src/services/storage/entity/UserOffer.ts +++ b/src/services/storage/entity/UserOffer.ts @@ -13,8 +13,8 @@ export class UserOffer { @Column({ unique: true, nullable: false }) offer_id: string - @Column({ type: "text", nullable: true }) - managing_app_pubkey: string | null + @Column({ default: "" }) + management_pubkey: string @Column() label: string diff --git a/src/services/storage/managementStorage.ts b/src/services/storage/managementStorage.ts index 3a7e7fd6..6ff5a8b0 100644 --- a/src/services/storage/managementStorage.ts +++ b/src/services/storage/managementStorage.ts @@ -7,11 +7,11 @@ export class ManagementStorage { this.dbs = dbs; } - getGrant(user_id: string, app_pubkey: string) { - return this.dbs.FindOne('ManagementGrant' as any, { where: { user_id, app_pubkey } }); + getGrant(appUserId: string, appPubkey: string) { + return this.dbs.FindOne('ManagementGrant', { where: { app_pubkey: appPubkey, app_user_id: appUserId } }); } - async addGrant(user_id: string, app_pubkey: string, expires_at?: Date) { - return this.dbs.CreateAndSave('ManagementGrant' as any, { user_id, app_pubkey, expires_at }); + async addGrant(appUserId: string, appPubkey: string, expires_at_unix: number) { + return this.dbs.CreateAndSave('ManagementGrant', { app_user_id: appUserId, app_pubkey: appPubkey, expires_at_unix }); } } \ No newline at end of file diff --git a/src/services/storage/offerStorage.ts b/src/services/storage/offerStorage.ts index 2a921c57..4e6ff657 100644 --- a/src/services/storage/offerStorage.ts +++ b/src/services/storage/offerStorage.ts @@ -34,6 +34,11 @@ export default class { async GetUserOffers(app_user_id: string): Promise { return this.dbs.Find('UserOffer', { where: { app_user_id } }) } + + async getManagedUserOffers(app_user_id: string, management_pubkey: string): Promise { + return this.dbs.Find('UserOffer', { where: { app_user_id, management_pubkey } }) + } + async GetUserOffer(app_user_id: string, offer_id: string): Promise { return this.dbs.FindOne('UserOffer', { where: { app_user_id, offer_id } }) } From 136a9ad231ca4c17db8265bce5e130cf6cc2754f Mon Sep 17 00:00:00 2001 From: boufni95 Date: Mon, 30 Jun 2025 18:22:57 +0000 Subject: [PATCH 09/24] fixies --- datasource.js | 5 +- package-lock.json | 8 +-- package.json | 2 +- src/nostrMiddleware.ts | 3 +- src/services/main/index.ts | 4 +- src/services/storage/db/db.ts | 4 +- .../storage/entity/ManagementGrant.ts | 2 +- ...1749933500426-AddOfferManagingAppPubKey.ts | 14 ------ .../1749934345873-CreateManagementGrant.ts | 50 ------------------- .../1751307732346-management_grant.ts | 22 ++++++++ src/services/storage/migrations/runner.ts | 3 +- 11 files changed, 39 insertions(+), 78 deletions(-) delete mode 100644 src/services/storage/migrations/1749933500426-AddOfferManagingAppPubKey.ts delete mode 100644 src/services/storage/migrations/1749934345873-CreateManagementGrant.ts create mode 100644 src/services/storage/migrations/1751307732346-management_grant.ts diff --git a/datasource.js b/datasource.js index 8b250b72..e599e1ca 100644 --- a/datasource.js +++ b/datasource.js @@ -17,6 +17,7 @@ import { TrackedProvider } from "./build/src/services/storage/entity/TrackedProv import { InviteToken } from "./build/src/services/storage/entity/InviteToken.js" import { DebitAccess } from "./build/src/services/storage/entity/DebitAccess.js" import { UserOffer } from "./build/src/services/storage/entity/UserOffer.js" +import { ManagementGrant } from "./build/src/services/storage/entity/ManagementGrant.js" import { Initial1703170309875 } from './build/src/services/storage/migrations/1703170309875-initial.js' import { LspOrder1718387847693 } from './build/src/services/storage/migrations/1718387847693-lsp_order.js' @@ -35,7 +36,7 @@ export default new DataSource({ // logging: true, migrations: [Initial1703170309875, LspOrder1718387847693, LiquidityProvider1719335699480, LndNodeInfo1720187506189, CreateInviteTokenTable1721751414878, PaymentIndex1721760297610, DebitAccess1726496225078, DebitAccessFixes1726685229264, DebitToPub1727105758354, UserCbUrl1727112281043, UserOffer1733502626042], entities: [User, UserReceivingInvoice, UserReceivingAddress, AddressReceivingTransaction, UserInvoicePayment, UserTransactionPayment, - UserBasicAuth, UserEphemeralKey, Product, UserToUserPayment, Application, ApplicationUser, UserToUserPayment, LspOrder, LndNodeInfo, TrackedProvider, InviteToken, DebitAccess, UserOffer], + UserBasicAuth, UserEphemeralKey, Product, UserToUserPayment, Application, ApplicationUser, UserToUserPayment, LspOrder, LndNodeInfo, TrackedProvider, InviteToken, DebitAccess, UserOffer, ManagementGrant], // synchronize: true, }) -//npx typeorm migration:generate ./src/services/storage/migrations/ops_time -d ./datasource.js \ No newline at end of file +//npx typeorm migration:generate ./src/services/storage/migrations/management_grant -d ./datasource.js \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 8d642916..14264ba5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,7 +13,7 @@ "@protobuf-ts/grpc-transport": "^2.9.4", "@protobuf-ts/plugin": "^2.5.0", "@protobuf-ts/runtime": "^2.5.0", - "@shocknet/clink-sdk": "^1.1.2", + "@shocknet/clink-sdk": "^1.1.4", "@stablelib/xchacha20": "^1.0.1", "@types/express": "^4.17.21", "@types/node": "^17.0.31", @@ -591,9 +591,9 @@ } }, "node_modules/@shocknet/clink-sdk": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@shocknet/clink-sdk/-/clink-sdk-1.1.2.tgz", - "integrity": "sha512-nICsXlLZRIs6E+wy3PfQccIidmQ/D7uSHfHfqrJzNJFOUH2+XGDkApB9TQU1eTrNgD/BHxm9tSZkEmG0it7I3w==", + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@shocknet/clink-sdk/-/clink-sdk-1.1.4.tgz", + "integrity": "sha512-b0YVsisIkTxOAwxrb1a9DGDxwWkHm7kJ2BpqOzkEbtJ6flkJxo2ggmRH3fxsVIiJOeVWwgSPATab68JU8DSLOA==", "license": "ISC", "dependencies": { "@noble/hashes": "^1.8.0", diff --git a/package.json b/package.json index 63ef6c1e..9894c250 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,7 @@ "@protobuf-ts/grpc-transport": "^2.9.4", "@protobuf-ts/plugin": "^2.5.0", "@protobuf-ts/runtime": "^2.5.0", - "@shocknet/clink-sdk": "^1.1.2", + "@shocknet/clink-sdk": "^1.1.4", "@stablelib/xchacha20": "^1.0.1", "@types/express": "^4.17.21", "@types/node": "^17.0.31", diff --git a/src/nostrMiddleware.ts b/src/nostrMiddleware.ts index 3c6d4434..cac2662c 100644 --- a/src/nostrMiddleware.ts +++ b/src/nostrMiddleware.ts @@ -4,8 +4,7 @@ import { NostrEvent, NostrSend, NostrSettings } from "./services/nostr/handler.j import * as Types from '../proto/autogenerated/ts/types.js' import NewNostrTransport, { NostrRequest } from '../proto/autogenerated/ts/nostr_transport.js'; import { ERROR, getLogger } from "./services/helpers/logger.js"; -import { NdebitData, NofferData } from "@shocknet/clink-sdk"; -import { NmanageRequest } from "./services/main/managementManager.js"; +import { NdebitData, NofferData, NmanageRequest } from "@shocknet/clink-sdk"; export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSettings: NostrSettings, onClientEvent: (e: { requestId: string }, fromPub: string) => void): { Stop: () => void, Send: NostrSend, Ping: () => Promise } => { const log = getLogger({}) diff --git a/src/services/main/index.ts b/src/services/main/index.ts index 22f6c31a..5c839d08 100644 --- a/src/services/main/index.ts +++ b/src/services/main/index.ts @@ -77,8 +77,8 @@ export default class { this.applicationManager = new ApplicationManager(this.storage, this.settings, this.paymentManager) this.appUserManager = new AppUserManager(this.storage, this.settings, this.applicationManager) this.debitManager = new DebitManager(this.storage, this.lnd, this.applicationManager) - this.offerManager = new OfferManager(this.storage, this.lnd, this.applicationManager, this.productManager, this.liquidityManager) - this.managementManager = new ManagementManager(this.storage, this.offerManager) + this.offerManager = new OfferManager(this.storage, this.settings, this.lnd, this.applicationManager, this.productManager, this.liquidityManager) + this.managementManager = new ManagementManager(this.storage, this.settings) //this.webRTC = new webRTC(this.storage, this.utils) } diff --git a/src/services/storage/db/db.ts b/src/services/storage/db/db.ts index 12e8b396..197b635d 100644 --- a/src/services/storage/db/db.ts +++ b/src/services/storage/db/db.ts @@ -24,6 +24,7 @@ import { InviteToken } from "../entity/InviteToken.js" import { DebitAccess } from "../entity/DebitAccess.js" import { RootOperation } from "../entity/RootOperation.js" import { UserOffer } from "../entity/UserOffer.js" +import { ManagementGrant } from "../entity/ManagementGrant.js" export type DbSettings = { @@ -65,7 +66,8 @@ export const MainDbEntities = { 'InviteToken': InviteToken, 'DebitAccess': DebitAccess, 'UserOffer': UserOffer, - 'Product': Product + 'Product': Product, + 'ManagementGrant': ManagementGrant } export type MainDbNames = keyof typeof MainDbEntities export const MainDbEntitiesNames = Object.keys(MainDbEntities) diff --git a/src/services/storage/entity/ManagementGrant.ts b/src/services/storage/entity/ManagementGrant.ts index 978cc236..46a962cd 100644 --- a/src/services/storage/entity/ManagementGrant.ts +++ b/src/services/storage/entity/ManagementGrant.ts @@ -1,7 +1,7 @@ import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, ManyToOne, JoinColumn, UpdateDateColumn } from "typeorm"; import { User } from "./User"; -@Entity("management_grants") +@Entity() export class ManagementGrant { @PrimaryGeneratedColumn() serial_id: number diff --git a/src/services/storage/migrations/1749933500426-AddOfferManagingAppPubKey.ts b/src/services/storage/migrations/1749933500426-AddOfferManagingAppPubKey.ts deleted file mode 100644 index 2585e67f..00000000 --- a/src/services/storage/migrations/1749933500426-AddOfferManagingAppPubKey.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class AddOfferManagingAppPubKey1749933500426 implements MigrationInterface { - name = 'AddOfferManagingAppPubKey1749933500426' - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "user_offer" ADD "managing_app_pubkey" character varying`); - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "user_offer" DROP COLUMN "managing_app_pubkey"`); - } - -} diff --git a/src/services/storage/migrations/1749934345873-CreateManagementGrant.ts b/src/services/storage/migrations/1749934345873-CreateManagementGrant.ts deleted file mode 100644 index a14838a1..00000000 --- a/src/services/storage/migrations/1749934345873-CreateManagementGrant.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { MigrationInterface, QueryRunner, Table, TableForeignKey } from "typeorm" - -export class CreateManagementGrant1749934345873 implements MigrationInterface { - name = 'CreateManagementGrant1749934345873' - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.createTable(new Table({ - name: "management_grants", - columns: [ - { - name: "id", - type: "varchar", - isPrimary: true, - isGenerated: true, - generationStrategy: "uuid" - }, - { - name: "user_id", - type: "varchar" - }, - { - name: "app_pubkey", - type: "varchar" - }, - { - name: "created_at", - type: "timestamp", - default: "CURRENT_TIMESTAMP" - }, - { - name: "expires_at", - type: "timestamp", - isNullable: true - } - ] - })); - - await queryRunner.createForeignKey("management_grants", new TableForeignKey({ - columnNames: ["user_id"], - referencedColumnNames: ["user_id"], - referencedTableName: "user", - onDelete: "CASCADE" - })); - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.dropTable("management_grants"); - } - -} diff --git a/src/services/storage/migrations/1751307732346-management_grant.ts b/src/services/storage/migrations/1751307732346-management_grant.ts new file mode 100644 index 00000000..170fba69 --- /dev/null +++ b/src/services/storage/migrations/1751307732346-management_grant.ts @@ -0,0 +1,22 @@ +import { MigrationInterface, QueryRunner } from "typeorm"; + +export class ManagementGrant1751307732346 implements MigrationInterface { + name = 'ManagementGrant1751307732346' + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(`CREATE TABLE "management_grant" ("serial_id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "app_user_id" varchar NOT NULL, "app_pubkey" varchar NOT NULL, "expires_at_unix" integer NOT NULL, "created_at" datetime NOT NULL DEFAULT (datetime('now')), "updated_at" datetime NOT NULL DEFAULT (datetime('now')))`); + await queryRunner.query(`CREATE TABLE "temporary_user_offer" ("serial_id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "app_user_id" varchar NOT NULL, "offer_id" varchar NOT NULL, "label" varchar NOT NULL, "price_sats" integer NOT NULL DEFAULT (0), "callback_url" varchar NOT NULL DEFAULT (''), "expected_data" text, "created_at" datetime NOT NULL DEFAULT (datetime('now')), "updated_at" datetime NOT NULL DEFAULT (datetime('now')), "management_pubkey" varchar NOT NULL DEFAULT (''), CONSTRAINT "UQ_478f72095abd8a516d3a309a5c5" UNIQUE ("offer_id"))`); + await queryRunner.query(`INSERT INTO "temporary_user_offer"("serial_id", "app_user_id", "offer_id", "label", "price_sats", "callback_url", "expected_data", "created_at", "updated_at") SELECT "serial_id", "app_user_id", "offer_id", "label", "price_sats", "callback_url", "expected_data", "created_at", "updated_at" FROM "user_offer"`); + await queryRunner.query(`DROP TABLE "user_offer"`); + await queryRunner.query(`ALTER TABLE "temporary_user_offer" RENAME TO "user_offer"`); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE "user_offer" RENAME TO "temporary_user_offer"`); + await queryRunner.query(`CREATE TABLE "user_offer" ("serial_id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "app_user_id" varchar NOT NULL, "offer_id" varchar NOT NULL, "label" varchar NOT NULL, "price_sats" integer NOT NULL DEFAULT (0), "callback_url" varchar NOT NULL DEFAULT (''), "expected_data" text, "created_at" datetime NOT NULL DEFAULT (datetime('now')), "updated_at" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_478f72095abd8a516d3a309a5c5" UNIQUE ("offer_id"))`); + await queryRunner.query(`INSERT INTO "user_offer"("serial_id", "app_user_id", "offer_id", "label", "price_sats", "callback_url", "expected_data", "created_at", "updated_at") SELECT "serial_id", "app_user_id", "offer_id", "label", "price_sats", "callback_url", "expected_data", "created_at", "updated_at" FROM "temporary_user_offer"`); + await queryRunner.query(`DROP TABLE "temporary_user_offer"`); + await queryRunner.query(`DROP TABLE "management_grant"`); + } + +} diff --git a/src/services/storage/migrations/runner.ts b/src/services/storage/migrations/runner.ts index d2ee0082..be0eedfe 100644 --- a/src/services/storage/migrations/runner.ts +++ b/src/services/storage/migrations/runner.ts @@ -16,7 +16,8 @@ import { UserCbUrl1727112281043 } from './1727112281043-user_cb_url.js' import { RootOps1732566440447 } from './1732566440447-root_ops.js' import { UserOffer1733502626042 } from './1733502626042-user_offer.js' import { RootOpsTime1745428134124 } from './1745428134124-root_ops_time.js' -export const allMigrations = [Initial1703170309875, LspOrder1718387847693, LiquidityProvider1719335699480, LndNodeInfo1720187506189, TrackedProvider1720814323679, CreateInviteTokenTable1721751414878, PaymentIndex1721760297610, DebitAccess1726496225078, DebitAccessFixes1726685229264, DebitToPub1727105758354, UserCbUrl1727112281043, UserOffer1733502626042] +import { ManagementGrant1751307732346 } from './1751307732346-management_grant.js' +export const allMigrations = [Initial1703170309875, LspOrder1718387847693, LiquidityProvider1719335699480, LndNodeInfo1720187506189, TrackedProvider1720814323679, CreateInviteTokenTable1721751414878, PaymentIndex1721760297610, DebitAccess1726496225078, DebitAccessFixes1726685229264, DebitToPub1727105758354, UserCbUrl1727112281043, UserOffer1733502626042, ManagementGrant1751307732346] export const allMetricsMigrations = [LndMetrics1703170330183, ChannelRouting1709316653538, HtlcCount1724266887195, BalanceEvents1724860966825, RootOps1732566440447, RootOpsTime1745428134124] /* export const TypeOrmMigrationRunner = async (log: PubLogger, storageManager: Storage, settings: DbSettings, arg: string | undefined): Promise => { await connectAndMigrate(log, storageManager, allMigrations, allMetricsMigrations) From df088bf0fed55ad1183fce20ad377f23d410dd1f Mon Sep 17 00:00:00 2001 From: boufni95 Date: Tue, 8 Jul 2025 15:41:41 +0000 Subject: [PATCH 10/24] manage authorization --- datasource.js | 7 +- package-lock.json | 8 +- package.json | 2 +- proto/autogenerated/client.md | 53 +++++++ proto/autogenerated/go/http_client.go | 55 +++++++ proto/autogenerated/go/types.go | 17 +++ proto/autogenerated/ts/express_server.ts | 63 ++++++++ proto/autogenerated/ts/http_client.ts | 29 ++++ proto/autogenerated/ts/nostr_client.ts | 44 ++++++ proto/autogenerated/ts/nostr_transport.ts | 64 ++++++++ proto/autogenerated/ts/types.ts | 119 ++++++++++++++- proto/service/methods.proto | 20 +++ proto/service/structs.proto | 21 +++ src/services/main/managementManager.ts | 139 ++++++++++++------ src/services/serverMethods/index.ts | 7 + .../storage/entity/ManagementGrant.ts | 3 + src/services/storage/managementStorage.ts | 8 +- .../1751989251513-management_grant_banned.ts | 20 +++ 18 files changed, 623 insertions(+), 56 deletions(-) create mode 100644 src/services/storage/migrations/1751989251513-management_grant_banned.ts diff --git a/datasource.js b/datasource.js index e599e1ca..c2b68147 100644 --- a/datasource.js +++ b/datasource.js @@ -30,13 +30,16 @@ import { DebitAccessFixes1726685229264 } from './build/src/services/storage/migr import { DebitToPub1727105758354 } from './build/src/services/storage/migrations/1727105758354-debit_to_pub.js' import { UserCbUrl1727112281043 } from './build/src/services/storage/migrations/1727112281043-user_cb_url.js' import { UserOffer1733502626042 } from './build/src/services/storage/migrations/1733502626042-user_offer.js' +import { ManagementGrant1751307732346 } from './build/src/services/storage/migrations/1751307732346-management_grant.js' export default new DataSource({ type: "sqlite", database: "db.sqlite", // logging: true, - migrations: [Initial1703170309875, LspOrder1718387847693, LiquidityProvider1719335699480, LndNodeInfo1720187506189, CreateInviteTokenTable1721751414878, PaymentIndex1721760297610, DebitAccess1726496225078, DebitAccessFixes1726685229264, DebitToPub1727105758354, UserCbUrl1727112281043, UserOffer1733502626042], + migrations: [Initial1703170309875, LspOrder1718387847693, LiquidityProvider1719335699480, LndNodeInfo1720187506189, CreateInviteTokenTable1721751414878, + PaymentIndex1721760297610, DebitAccess1726496225078, DebitAccessFixes1726685229264, DebitToPub1727105758354, UserCbUrl1727112281043, + UserOffer1733502626042, ManagementGrant1751307732346], entities: [User, UserReceivingInvoice, UserReceivingAddress, AddressReceivingTransaction, UserInvoicePayment, UserTransactionPayment, UserBasicAuth, UserEphemeralKey, Product, UserToUserPayment, Application, ApplicationUser, UserToUserPayment, LspOrder, LndNodeInfo, TrackedProvider, InviteToken, DebitAccess, UserOffer, ManagementGrant], // synchronize: true, }) -//npx typeorm migration:generate ./src/services/storage/migrations/management_grant -d ./datasource.js \ No newline at end of file +//npx typeorm migration:generate ./src/services/storage/migrations/management_grant_banned -d ./datasource.js \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 14264ba5..a1f745cd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,7 +13,7 @@ "@protobuf-ts/grpc-transport": "^2.9.4", "@protobuf-ts/plugin": "^2.5.0", "@protobuf-ts/runtime": "^2.5.0", - "@shocknet/clink-sdk": "^1.1.4", + "@shocknet/clink-sdk": "^1.1.6", "@stablelib/xchacha20": "^1.0.1", "@types/express": "^4.17.21", "@types/node": "^17.0.31", @@ -591,9 +591,9 @@ } }, "node_modules/@shocknet/clink-sdk": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@shocknet/clink-sdk/-/clink-sdk-1.1.4.tgz", - "integrity": "sha512-b0YVsisIkTxOAwxrb1a9DGDxwWkHm7kJ2BpqOzkEbtJ6flkJxo2ggmRH3fxsVIiJOeVWwgSPATab68JU8DSLOA==", + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/@shocknet/clink-sdk/-/clink-sdk-1.1.6.tgz", + "integrity": "sha512-PXNXdaS5sFIgfdWV5yMW0/ghrORAEVTy9K3fY4j/Rf4fjbNspBAaDioYn7to+lU/boPUxRMmFE0ix/2Mr6pkFQ==", "license": "ISC", "dependencies": { "@noble/hashes": "^1.8.0", diff --git a/package.json b/package.json index 9894c250..c3ea45d3 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,7 @@ "@protobuf-ts/grpc-transport": "^2.9.4", "@protobuf-ts/plugin": "^2.5.0", "@protobuf-ts/runtime": "^2.5.0", - "@shocknet/clink-sdk": "^1.1.4", + "@shocknet/clink-sdk": "^1.1.6", "@stablelib/xchacha20": "^1.0.1", "@types/express": "^4.17.21", "@types/node": "^17.0.31", diff --git a/proto/autogenerated/client.md b/proto/autogenerated/client.md index 16aef4db..bacdf85c 100644 --- a/proto/autogenerated/client.md +++ b/proto/autogenerated/client.md @@ -43,6 +43,11 @@ The nostr server will send back a message response, and inside the body there wi - input: [DebitAuthorizationRequest](#DebitAuthorizationRequest) - output: [DebitAuthorization](#DebitAuthorization) +- AuthorizeManage + - auth type: __User__ + - input: [ManageAuthorizationRequest](#ManageAuthorizationRequest) + - output: [ManageAuthorization](#ManageAuthorization) + - BanDebit - auth type: __User__ - input: [DebitOperation](#DebitOperation) @@ -128,6 +133,11 @@ The nostr server will send back a message response, and inside the body there wi - This methods has an __empty__ __request__ body - output: [LiveDebitRequest](#LiveDebitRequest) +- GetLiveManageRequests + - auth type: __User__ + - This methods has an __empty__ __request__ body + - output: [LiveManageRequest](#LiveManageRequest) + - GetLiveUserOperations - auth type: __User__ - This methods has an __empty__ __request__ body @@ -153,6 +163,11 @@ The nostr server will send back a message response, and inside the body there wi - This methods has an __empty__ __request__ body - output: [LnurlLinkResponse](#LnurlLinkResponse) +- GetManageAuthorizations + - auth type: __User__ + - This methods has an __empty__ __request__ body + - output: [ManageAuthorizations](#ManageAuthorizations) + - GetMigrationUpdate - auth type: __User__ - This methods has an __empty__ __request__ body @@ -418,6 +433,13 @@ The nostr server will send back a message response, and inside the body there wi - input: [DebitAuthorizationRequest](#DebitAuthorizationRequest) - output: [DebitAuthorization](#DebitAuthorization) +- AuthorizeManage + - auth type: __User__ + - http method: __post__ + - http route: __/api/user/manage/authorize__ + - input: [ManageAuthorizationRequest](#ManageAuthorizationRequest) + - output: [ManageAuthorization](#ManageAuthorization) + - BanDebit - auth type: __User__ - http method: __post__ @@ -565,6 +587,13 @@ The nostr server will send back a message response, and inside the body there wi - This methods has an __empty__ __request__ body - output: [LiveDebitRequest](#LiveDebitRequest) +- GetLiveManageRequests + - auth type: __User__ + - http method: __post__ + - http route: __/api/user/manage/sub__ + - This methods has an __empty__ __request__ body + - output: [LiveManageRequest](#LiveManageRequest) + - GetLiveUserOperations - auth type: __User__ - http method: __post__ @@ -618,6 +647,13 @@ The nostr server will send back a message response, and inside the body there wi - This methods has an __empty__ __request__ body - output: [LnurlLinkResponse](#LnurlLinkResponse) +- GetManageAuthorizations + - auth type: __User__ + - http method: __get__ + - http route: __/api/user/manage/get__ + - This methods has an __empty__ __request__ body + - output: [ManageAuthorizations](#ManageAuthorizations) + - GetMigrationUpdate - auth type: __User__ - http method: __post__ @@ -1216,6 +1252,10 @@ The nostr server will send back a message response, and inside the body there wi - __npub__: _string_ - __request_id__: _string_ +### LiveManageRequest + - __npub__: _string_ + - __request_id__: _string_ + ### LiveUserOperation - __operation__: _[UserOperation](#UserOperation)_ @@ -1290,6 +1330,19 @@ The nostr server will send back a message response, and inside the body there wi - __payLink__: _string_ - __tag__: _string_ +### ManageAuthorization + - __authorized__: _boolean_ + - __manage_id__: _string_ + - __npub__: _string_ + +### ManageAuthorizationRequest + - __authorize_npub__: _string_ + - __ban__: _boolean_ + - __request_id__: _string_ *this field is optional + +### ManageAuthorizations + - __manages__: ARRAY of: _[ManageAuthorization](#ManageAuthorization)_ + ### MetricsFile ### MigrationUpdate diff --git a/proto/autogenerated/go/http_client.go b/proto/autogenerated/go/http_client.go index bd9a32f0..3971791f 100644 --- a/proto/autogenerated/go/http_client.go +++ b/proto/autogenerated/go/http_client.go @@ -63,6 +63,7 @@ type Client struct { AddUserOffer func(req OfferConfig) (*OfferId, error) AuthApp func(req AuthAppRequest) (*AuthApp, error) AuthorizeDebit func(req DebitAuthorizationRequest) (*DebitAuthorization, error) + AuthorizeManage func(req ManageAuthorizationRequest) (*ManageAuthorization, error) BanDebit func(req DebitOperation) error BanUser func(req BanUserRequest) (*BanUserResponse, error) // batching method: BatchUser not implemented @@ -84,6 +85,7 @@ type Client struct { GetInviteLinkState func(req GetInviteTokenStateRequest) (*GetInviteTokenStateResponse, error) GetLNURLChannelLink func() (*LnurlLinkResponse, error) GetLiveDebitRequests func() (*LiveDebitRequest, error) + GetLiveManageRequests func() (*LiveManageRequest, error) GetLiveUserOperations func() (*LiveUserOperation, error) GetLndForwardingMetrics func(req LndMetricsRequest) (*LndForwardingMetrics, error) GetLndMetrics func(req LndMetricsRequest) (*LndMetrics, error) @@ -91,6 +93,7 @@ type Client struct { GetLnurlPayLink func() (*LnurlLinkResponse, error) GetLnurlWithdrawInfo func(query GetLnurlWithdrawInfo_Query) (*LnurlWithdrawInfoResponse, error) GetLnurlWithdrawLink func() (*LnurlLinkResponse, error) + GetManageAuthorizations func() (*ManageAuthorizations, error) GetMigrationUpdate func() (*MigrationUpdate, error) GetNPubLinkingState func(req GetNPubLinking) (*NPubLinking, error) GetPaymentState func(req GetPaymentStateRequest) (*PaymentState, error) @@ -397,6 +400,35 @@ func NewClient(params ClientParams) *Client { } return &res, nil }, + AuthorizeManage: func(req ManageAuthorizationRequest) (*ManageAuthorization, error) { + auth, err := params.RetrieveUserAuth() + if err != nil { + return nil, err + } + finalRoute := "/api/user/manage/authorize" + body, err := json.Marshal(req) + if err != nil { + return nil, err + } + resBody, err := doPostRequest(params.BaseURL+finalRoute, body, auth) + if err != nil { + return nil, err + } + result := ResultError{} + err = json.Unmarshal(resBody, &result) + if err != nil { + return nil, err + } + if result.Status == "ERROR" { + return nil, fmt.Errorf(result.Reason) + } + res := ManageAuthorization{} + err = json.Unmarshal(resBody, &res) + if err != nil { + return nil, err + } + return &res, nil + }, BanDebit: func(req DebitOperation) error { auth, err := params.RetrieveUserAuth() if err != nil { @@ -906,6 +938,7 @@ func NewClient(params ClientParams) *Client { return &res, nil }, // server streaming method: GetLiveDebitRequests not implemented + // server streaming method: GetLiveManageRequests not implemented // server streaming method: GetLiveUserOperations not implemented GetLndForwardingMetrics: func(req LndMetricsRequest) (*LndForwardingMetrics, error) { auth, err := params.RetrieveMetricsAuth() @@ -1069,6 +1102,28 @@ func NewClient(params ClientParams) *Client { } return &res, nil }, + GetManageAuthorizations: func() (*ManageAuthorizations, error) { + auth, err := params.RetrieveUserAuth() + if err != nil { + return nil, err + } + finalRoute := "/api/user/manage/get" + resBody, err := doGetRequest(params.BaseURL+finalRoute, auth) + result := ResultError{} + err = json.Unmarshal(resBody, &result) + if err != nil { + return nil, err + } + if result.Status == "ERROR" { + return nil, fmt.Errorf(result.Reason) + } + res := ManageAuthorizations{} + err = json.Unmarshal(resBody, &res) + if err != nil { + return nil, err + } + return &res, nil + }, // server streaming method: GetMigrationUpdate not implemented GetNPubLinkingState: func(req GetNPubLinking) (*NPubLinking, error) { auth, err := params.RetrieveAppAuth() diff --git a/proto/autogenerated/go/types.go b/proto/autogenerated/go/types.go index 9a1b63ff..4f797f59 100644 --- a/proto/autogenerated/go/types.go +++ b/proto/autogenerated/go/types.go @@ -355,6 +355,10 @@ type LiveDebitRequest struct { Npub string `json:"npub"` Request_id string `json:"request_id"` } +type LiveManageRequest struct { + Npub string `json:"npub"` + Request_id string `json:"request_id"` +} type LiveUserOperation struct { Operation *UserOperation `json:"operation"` } @@ -429,6 +433,19 @@ type LnurlWithdrawInfoResponse struct { Paylink string `json:"payLink"` Tag string `json:"tag"` } +type ManageAuthorization struct { + Authorized bool `json:"authorized"` + Manage_id string `json:"manage_id"` + Npub string `json:"npub"` +} +type ManageAuthorizationRequest struct { + Authorize_npub string `json:"authorize_npub"` + Ban bool `json:"ban"` + Request_id string `json:"request_id"` +} +type ManageAuthorizations struct { + Manages []ManageAuthorization `json:"manages"` +} type MetricsFile struct { } type MigrationUpdate struct { diff --git a/proto/autogenerated/ts/express_server.ts b/proto/autogenerated/ts/express_server.ts index 8e6e04f2..b7b4a73f 100644 --- a/proto/autogenerated/ts/express_server.ts +++ b/proto/autogenerated/ts/express_server.ts @@ -232,6 +232,28 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => { opts.metricsCallback([{ ...info, ...stats, ...authContext }]) } catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } }) + if (!opts.allowNotImplementedMethods && !methods.AuthorizeManage) throw new Error('method: AuthorizeManage is not implemented') + app.post('/api/user/manage/authorize', async (req, res) => { + const info: Types.RequestInfo = { rpcName: 'AuthorizeManage', batch: false, nostr: false, batchSize: 0} + const stats: Types.RequestStats = { startMs:req.startTimeMs || 0, start:req.startTime || 0n, parse: process.hrtime.bigint(), guard: 0n, validate: 0n, handle: 0n } + let authCtx: Types.AuthContext = {} + try { + if (!methods.AuthorizeManage) throw new Error('method: AuthorizeManage is not implemented') + const authContext = await opts.UserAuthGuard(req.headers['authorization']) + authCtx = authContext + stats.guard = process.hrtime.bigint() + const request = req.body + const error = Types.ManageAuthorizationRequestValidate(request) + stats.validate = process.hrtime.bigint() + if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback) + const query = req.query + const params = req.params + const response = await methods.AuthorizeManage({rpcName:'AuthorizeManage', ctx:authContext , req: request}) + stats.handle = process.hrtime.bigint() + res.json({status: 'OK', ...response}) + opts.metricsCallback([{ ...info, ...stats, ...authContext }]) + } catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } + }) if (!opts.allowNotImplementedMethods && !methods.BanDebit) throw new Error('method: BanDebit is not implemented') app.post('/api/user/debit/ban', async (req, res) => { const info: Types.RequestInfo = { rpcName: 'BanDebit', batch: false, nostr: false, batchSize: 0} @@ -333,6 +355,18 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => { callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) } break + case 'AuthorizeManage': + if (!methods.AuthorizeManage) { + throw new Error('method AuthorizeManage not found' ) + } else { + const error = Types.ManageAuthorizationRequestValidate(operation.req) + opStats.validate = process.hrtime.bigint() + if (error !== null) throw error + const res = await methods.AuthorizeManage({...operation, ctx}); responses.push({ status: 'OK', ...res }) + opStats.handle = process.hrtime.bigint() + callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) + } + break case 'BanDebit': if (!methods.BanDebit) { throw new Error('method BanDebit not found' ) @@ -443,6 +477,16 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => { callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) } break + case 'GetManageAuthorizations': + if (!methods.GetManageAuthorizations) { + throw new Error('method GetManageAuthorizations not found' ) + } else { + opStats.validate = opStats.guard + const res = await methods.GetManageAuthorizations({...operation, ctx}); responses.push({ status: 'OK', ...res }) + opStats.handle = process.hrtime.bigint() + callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) + } + break case 'GetPaymentState': if (!methods.GetPaymentState) { throw new Error('method GetPaymentState not found' ) @@ -1116,6 +1160,25 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => { opts.metricsCallback([{ ...info, ...stats, ...authContext }]) } catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } }) + if (!opts.allowNotImplementedMethods && !methods.GetManageAuthorizations) throw new Error('method: GetManageAuthorizations is not implemented') + app.get('/api/user/manage/get', async (req, res) => { + const info: Types.RequestInfo = { rpcName: 'GetManageAuthorizations', batch: false, nostr: false, batchSize: 0} + const stats: Types.RequestStats = { startMs:req.startTimeMs || 0, start:req.startTime || 0n, parse: process.hrtime.bigint(), guard: 0n, validate: 0n, handle: 0n } + let authCtx: Types.AuthContext = {} + try { + if (!methods.GetManageAuthorizations) throw new Error('method: GetManageAuthorizations is not implemented') + const authContext = await opts.UserAuthGuard(req.headers['authorization']) + authCtx = authContext + stats.guard = process.hrtime.bigint() + stats.validate = stats.guard + const query = req.query + const params = req.params + const response = await methods.GetManageAuthorizations({rpcName:'GetManageAuthorizations', ctx:authContext }) + stats.handle = process.hrtime.bigint() + res.json({status: 'OK', ...response}) + opts.metricsCallback([{ ...info, ...stats, ...authContext }]) + } catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } + }) if (!opts.allowNotImplementedMethods && !methods.GetNPubLinkingState) throw new Error('method: GetNPubLinkingState is not implemented') app.post('/api/app/user/npub/state', async (req, res) => { const info: Types.RequestInfo = { rpcName: 'GetNPubLinkingState', batch: false, nostr: false, batchSize: 0} diff --git a/proto/autogenerated/ts/http_client.ts b/proto/autogenerated/ts/http_client.ts index 5750aa3e..615265f4 100644 --- a/proto/autogenerated/ts/http_client.ts +++ b/proto/autogenerated/ts/http_client.ts @@ -140,6 +140,20 @@ export default (params: ClientParams) => ({ } return { status: 'ERROR', reason: 'invalid response' } }, + AuthorizeManage: async (request: Types.ManageAuthorizationRequest): Promise => { + const auth = await params.retrieveUserAuth() + if (auth === null) throw new Error('retrieveUserAuth() returned null') + let finalRoute = '/api/user/manage/authorize' + const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } }) + if (data.status === 'ERROR' && typeof data.reason === 'string') return data + if (data.status === 'OK') { + const result = data + if(!params.checkResult) return { status: 'OK', ...result } + const error = Types.ManageAuthorizationValidate(result) + if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message } + } + return { status: 'ERROR', reason: 'invalid response' } + }, BanDebit: async (request: Types.DebitOperation): Promise => { const auth = await params.retrieveUserAuth() if (auth === null) throw new Error('retrieveUserAuth() returned null') @@ -403,6 +417,7 @@ export default (params: ClientParams) => ({ return { status: 'ERROR', reason: 'invalid response' } }, GetLiveDebitRequests: async (cb: (v:ResultError | ({ status: 'OK' }& Types.LiveDebitRequest)) => void): Promise => { throw new Error('http streams are not supported')}, + GetLiveManageRequests: async (cb: (v:ResultError | ({ status: 'OK' }& Types.LiveManageRequest)) => void): Promise => { throw new Error('http streams are not supported')}, GetLiveUserOperations: async (cb: (v:ResultError | ({ status: 'OK' }& Types.LiveUserOperation)) => void): Promise => { throw new Error('http streams are not supported')}, GetLndForwardingMetrics: async (request: Types.LndMetricsRequest): Promise => { const auth = await params.retrieveMetricsAuth() @@ -492,6 +507,20 @@ export default (params: ClientParams) => ({ } return { status: 'ERROR', reason: 'invalid response' } }, + GetManageAuthorizations: async (): Promise => { + const auth = await params.retrieveUserAuth() + if (auth === null) throw new Error('retrieveUserAuth() returned null') + let finalRoute = '/api/user/manage/get' + const { data } = await axios.get(params.baseUrl + finalRoute, { headers: { 'authorization': auth } }) + if (data.status === 'ERROR' && typeof data.reason === 'string') return data + if (data.status === 'OK') { + const result = data + if(!params.checkResult) return { status: 'OK', ...result } + const error = Types.ManageAuthorizationsValidate(result) + if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message } + } + return { status: 'ERROR', reason: 'invalid response' } + }, GetMigrationUpdate: async (cb: (v:ResultError | ({ status: 'OK' }& Types.MigrationUpdate)) => void): Promise => { throw new Error('http streams are not supported')}, GetNPubLinkingState: async (request: Types.GetNPubLinking): Promise => { const auth = await params.retrieveAppAuth() diff --git a/proto/autogenerated/ts/nostr_client.ts b/proto/autogenerated/ts/nostr_client.ts index a08f4015..569c5842 100644 --- a/proto/autogenerated/ts/nostr_client.ts +++ b/proto/autogenerated/ts/nostr_client.ts @@ -99,6 +99,21 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ } return { status: 'ERROR', reason: 'invalid response' } }, + AuthorizeManage: async (request: Types.ManageAuthorizationRequest): Promise => { + const auth = await params.retrieveNostrUserAuth() + if (auth === null) throw new Error('retrieveNostrUserAuth() returned null') + const nostrRequest: NostrRequest = {} + nostrRequest.body = request + const data = await send(params.pubDestination, {rpcName:'AuthorizeManage',authIdentifier:auth, ...nostrRequest }) + if (data.status === 'ERROR' && typeof data.reason === 'string') return data + if (data.status === 'OK') { + const result = data + if(!params.checkResult) return { status: 'OK', ...result } + const error = Types.ManageAuthorizationValidate(result) + if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message } + } + return { status: 'ERROR', reason: 'invalid response' } + }, BanDebit: async (request: Types.DebitOperation): Promise => { const auth = await params.retrieveNostrUserAuth() if (auth === null) throw new Error('retrieveNostrUserAuth() returned null') @@ -334,6 +349,21 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ return cb({ status: 'ERROR', reason: 'invalid response' }) }) }, + GetLiveManageRequests: async (cb: (res:ResultError | ({ status: 'OK' }& Types.LiveManageRequest)) => void): Promise => { + const auth = await params.retrieveNostrUserAuth() + if (auth === null) throw new Error('retrieveNostrUserAuth() returned null') + const nostrRequest: NostrRequest = {} + subscribe(params.pubDestination, {rpcName:'GetLiveManageRequests',authIdentifier:auth, ...nostrRequest }, (data) => { + if (data.status === 'ERROR' && typeof data.reason === 'string') return cb(data) + if (data.status === 'OK') { + const result = data + if(!params.checkResult) return cb({ status: 'OK', ...result }) + const error = Types.LiveManageRequestValidate(result) + if (error === null) { return cb({ status: 'OK', ...result }) } else return cb({ status: 'ERROR', reason: error.message }) + } + return cb({ status: 'ERROR', reason: 'invalid response' }) + }) + }, GetLiveUserOperations: async (cb: (res:ResultError | ({ status: 'OK' }& Types.LiveUserOperation)) => void): Promise => { const auth = await params.retrieveNostrUserAuth() if (auth === null) throw new Error('retrieveNostrUserAuth() returned null') @@ -407,6 +437,20 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ } return { status: 'ERROR', reason: 'invalid response' } }, + GetManageAuthorizations: async (): Promise => { + const auth = await params.retrieveNostrUserAuth() + if (auth === null) throw new Error('retrieveNostrUserAuth() returned null') + const nostrRequest: NostrRequest = {} + const data = await send(params.pubDestination, {rpcName:'GetManageAuthorizations',authIdentifier:auth, ...nostrRequest }) + if (data.status === 'ERROR' && typeof data.reason === 'string') return data + if (data.status === 'OK') { + const result = data + if(!params.checkResult) return { status: 'OK', ...result } + const error = Types.ManageAuthorizationsValidate(result) + if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message } + } + return { status: 'ERROR', reason: 'invalid response' } + }, GetMigrationUpdate: async (cb: (res:ResultError | ({ status: 'OK' }& Types.MigrationUpdate)) => void): Promise => { const auth = await params.retrieveNostrUserAuth() if (auth === null) throw new Error('retrieveNostrUserAuth() returned null') diff --git a/proto/autogenerated/ts/nostr_transport.ts b/proto/autogenerated/ts/nostr_transport.ts index 5e9ea211..e7e93016 100644 --- a/proto/autogenerated/ts/nostr_transport.ts +++ b/proto/autogenerated/ts/nostr_transport.ts @@ -128,6 +128,22 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => { opts.metricsCallback([{ ...info, ...stats, ...authContext }]) }catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } break + case 'AuthorizeManage': + try { + if (!methods.AuthorizeManage) throw new Error('method: AuthorizeManage is not implemented') + const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier) + stats.guard = process.hrtime.bigint() + authCtx = authContext + const request = req.body + const error = Types.ManageAuthorizationRequestValidate(request) + stats.validate = process.hrtime.bigint() + if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback) + const response = await methods.AuthorizeManage({rpcName:'AuthorizeManage', ctx:authContext , req: request}) + stats.handle = process.hrtime.bigint() + res({status: 'OK', ...response}) + opts.metricsCallback([{ ...info, ...stats, ...authContext }]) + }catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } + break case 'BanDebit': try { if (!methods.BanDebit) throw new Error('method: BanDebit is not implemented') @@ -215,6 +231,18 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => { callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) } break + case 'AuthorizeManage': + if (!methods.AuthorizeManage) { + throw new Error('method not defined: AuthorizeManage') + } else { + const error = Types.ManageAuthorizationRequestValidate(operation.req) + opStats.validate = process.hrtime.bigint() + if (error !== null) throw error + const res = await methods.AuthorizeManage({...operation, ctx}); responses.push({ status: 'OK', ...res }) + opStats.handle = process.hrtime.bigint() + callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) + } + break case 'BanDebit': if (!methods.BanDebit) { throw new Error('method not defined: BanDebit') @@ -325,6 +353,16 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => { callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) } break + case 'GetManageAuthorizations': + if (!methods.GetManageAuthorizations) { + throw new Error('method not defined: GetManageAuthorizations') + } else { + opStats.validate = opStats.guard + const res = await methods.GetManageAuthorizations({...operation, ctx}); responses.push({ status: 'OK', ...res }) + opStats.handle = process.hrtime.bigint() + callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) + } + break case 'GetPaymentState': if (!methods.GetPaymentState) { throw new Error('method not defined: GetPaymentState') @@ -728,6 +766,19 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => { }}) }catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } break + case 'GetLiveManageRequests': + try { + if (!methods.GetLiveManageRequests) throw new Error('method: GetLiveManageRequests is not implemented') + const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier) + stats.guard = process.hrtime.bigint() + authCtx = authContext + stats.validate = stats.guard + methods.GetLiveManageRequests({rpcName:'GetLiveManageRequests', ctx:authContext ,cb: (response, err) => { + stats.handle = process.hrtime.bigint() + if (err) { logErrorAndReturnResponse(err, err.message, res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback)} else { res({status: 'OK', ...response});opts.metricsCallback([{ ...info, ...stats, ...authContext }])} + }}) + }catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } + break case 'GetLiveUserOperations': try { if (!methods.GetLiveUserOperations) throw new Error('method: GetLiveUserOperations is not implemented') @@ -799,6 +850,19 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => { opts.metricsCallback([{ ...info, ...stats, ...authContext }]) }catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } break + case 'GetManageAuthorizations': + try { + if (!methods.GetManageAuthorizations) throw new Error('method: GetManageAuthorizations is not implemented') + const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier) + stats.guard = process.hrtime.bigint() + authCtx = authContext + stats.validate = stats.guard + const response = await methods.GetManageAuthorizations({rpcName:'GetManageAuthorizations', ctx:authContext }) + stats.handle = process.hrtime.bigint() + res({status: 'OK', ...response}) + opts.metricsCallback([{ ...info, ...stats, ...authContext }]) + }catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } + break case 'GetMigrationUpdate': try { if (!methods.GetMigrationUpdate) throw new Error('method: GetMigrationUpdate is not implemented') diff --git a/proto/autogenerated/ts/types.ts b/proto/autogenerated/ts/types.ts index 9dc61dbd..21d59051 100644 --- a/proto/autogenerated/ts/types.ts +++ b/proto/autogenerated/ts/types.ts @@ -35,8 +35,8 @@ export type UserContext = { app_user_id: string user_id: string } -export type UserMethodInputs = AddProduct_Input | AddUserOffer_Input | AuthorizeDebit_Input | BanDebit_Input | DecodeInvoice_Input | DeleteUserOffer_Input | EditDebit_Input | EnrollAdminToken_Input | GetDebitAuthorizations_Input | GetHttpCreds_Input | GetLNURLChannelLink_Input | GetLnurlPayLink_Input | GetLnurlWithdrawLink_Input | GetPaymentState_Input | GetUserInfo_Input | GetUserOffer_Input | GetUserOfferInvoices_Input | GetUserOffers_Input | GetUserOperations_Input | NewAddress_Input | NewInvoice_Input | NewProductInvoice_Input | PayAddress_Input | PayInvoice_Input | ResetDebit_Input | RespondToDebit_Input | UpdateCallbackUrl_Input | UpdateUserOffer_Input | UserHealth_Input -export type UserMethodOutputs = AddProduct_Output | AddUserOffer_Output | AuthorizeDebit_Output | BanDebit_Output | DecodeInvoice_Output | DeleteUserOffer_Output | EditDebit_Output | EnrollAdminToken_Output | GetDebitAuthorizations_Output | GetHttpCreds_Output | GetLNURLChannelLink_Output | GetLnurlPayLink_Output | GetLnurlWithdrawLink_Output | GetPaymentState_Output | GetUserInfo_Output | GetUserOffer_Output | GetUserOfferInvoices_Output | GetUserOffers_Output | GetUserOperations_Output | NewAddress_Output | NewInvoice_Output | NewProductInvoice_Output | PayAddress_Output | PayInvoice_Output | ResetDebit_Output | RespondToDebit_Output | UpdateCallbackUrl_Output | UpdateUserOffer_Output | UserHealth_Output +export type UserMethodInputs = AddProduct_Input | AddUserOffer_Input | AuthorizeDebit_Input | AuthorizeManage_Input | BanDebit_Input | DecodeInvoice_Input | DeleteUserOffer_Input | EditDebit_Input | EnrollAdminToken_Input | GetDebitAuthorizations_Input | GetHttpCreds_Input | GetLNURLChannelLink_Input | GetLnurlPayLink_Input | GetLnurlWithdrawLink_Input | GetManageAuthorizations_Input | GetPaymentState_Input | GetUserInfo_Input | GetUserOffer_Input | GetUserOfferInvoices_Input | GetUserOffers_Input | GetUserOperations_Input | NewAddress_Input | NewInvoice_Input | NewProductInvoice_Input | PayAddress_Input | PayInvoice_Input | ResetDebit_Input | RespondToDebit_Input | UpdateCallbackUrl_Input | UpdateUserOffer_Input | UserHealth_Input +export type UserMethodOutputs = AddProduct_Output | AddUserOffer_Output | AuthorizeDebit_Output | AuthorizeManage_Output | BanDebit_Output | DecodeInvoice_Output | DeleteUserOffer_Output | EditDebit_Output | EnrollAdminToken_Output | GetDebitAuthorizations_Output | GetHttpCreds_Output | GetLNURLChannelLink_Output | GetLnurlPayLink_Output | GetLnurlWithdrawLink_Output | GetManageAuthorizations_Output | GetPaymentState_Output | GetUserInfo_Output | GetUserOffer_Output | GetUserOfferInvoices_Output | GetUserOffers_Output | GetUserOperations_Output | NewAddress_Output | NewInvoice_Output | NewProductInvoice_Output | PayAddress_Output | PayInvoice_Output | ResetDebit_Output | RespondToDebit_Output | UpdateCallbackUrl_Output | UpdateUserOffer_Output | UserHealth_Output export type AuthContext = AdminContext | AppContext | GuestContext | GuestWithPubContext | MetricsContext | UserContext export type AddApp_Input = {rpcName:'AddApp', req: AddAppRequest} @@ -66,6 +66,9 @@ export type AuthApp_Output = ResultError | ({ status: 'OK' } & AuthApp) export type AuthorizeDebit_Input = {rpcName:'AuthorizeDebit', req: DebitAuthorizationRequest} export type AuthorizeDebit_Output = ResultError | ({ status: 'OK' } & DebitAuthorization) +export type AuthorizeManage_Input = {rpcName:'AuthorizeManage', req: ManageAuthorizationRequest} +export type AuthorizeManage_Output = ResultError | ({ status: 'OK' } & ManageAuthorization) + export type BanDebit_Input = {rpcName:'BanDebit', req: DebitOperation} export type BanDebit_Output = ResultError | { status: 'OK' } @@ -129,6 +132,9 @@ export type GetLNURLChannelLink_Output = ResultError | ({ status: 'OK' } & Lnurl export type GetLiveDebitRequests_Input = {rpcName:'GetLiveDebitRequests', cb:(res: LiveDebitRequest, err:Error|null)=> void} export type GetLiveDebitRequests_Output = ResultError | { status: 'OK' } +export type GetLiveManageRequests_Input = {rpcName:'GetLiveManageRequests', cb:(res: LiveManageRequest, err:Error|null)=> void} +export type GetLiveManageRequests_Output = ResultError | { status: 'OK' } + export type GetLiveUserOperations_Input = {rpcName:'GetLiveUserOperations', cb:(res: LiveUserOperation, err:Error|null)=> void} export type GetLiveUserOperations_Output = ResultError | { status: 'OK' } @@ -156,6 +162,9 @@ export type GetLnurlWithdrawInfo_Output = ResultError | ({ status: 'OK' } & Lnur export type GetLnurlWithdrawLink_Input = {rpcName:'GetLnurlWithdrawLink'} export type GetLnurlWithdrawLink_Output = ResultError | ({ status: 'OK' } & LnurlLinkResponse) +export type GetManageAuthorizations_Input = {rpcName:'GetManageAuthorizations'} +export type GetManageAuthorizations_Output = ResultError | ({ status: 'OK' } & ManageAuthorizations) + export type GetMigrationUpdate_Input = {rpcName:'GetMigrationUpdate', cb:(res: MigrationUpdate, err:Error|null)=> void} export type GetMigrationUpdate_Output = ResultError | { status: 'OK' } @@ -320,6 +329,7 @@ export type ServerMethods = { AddUserOffer?: (req: AddUserOffer_Input & {ctx: UserContext }) => Promise AuthApp?: (req: AuthApp_Input & {ctx: AdminContext }) => Promise AuthorizeDebit?: (req: AuthorizeDebit_Input & {ctx: UserContext }) => Promise + AuthorizeManage?: (req: AuthorizeManage_Input & {ctx: UserContext }) => Promise BanDebit?: (req: BanDebit_Input & {ctx: UserContext }) => Promise BanUser?: (req: BanUser_Input & {ctx: AdminContext }) => Promise CloseChannel?: (req: CloseChannel_Input & {ctx: AdminContext }) => Promise @@ -340,6 +350,7 @@ export type ServerMethods = { GetInviteLinkState?: (req: GetInviteLinkState_Input & {ctx: AdminContext }) => Promise GetLNURLChannelLink?: (req: GetLNURLChannelLink_Input & {ctx: UserContext }) => Promise GetLiveDebitRequests?: (req: GetLiveDebitRequests_Input & {ctx: UserContext }) => Promise + GetLiveManageRequests?: (req: GetLiveManageRequests_Input & {ctx: UserContext }) => Promise GetLiveUserOperations?: (req: GetLiveUserOperations_Input & {ctx: UserContext }) => Promise GetLndForwardingMetrics?: (req: GetLndForwardingMetrics_Input & {ctx: MetricsContext }) => Promise GetLndMetrics?: (req: GetLndMetrics_Input & {ctx: MetricsContext }) => Promise @@ -347,6 +358,7 @@ export type ServerMethods = { GetLnurlPayLink?: (req: GetLnurlPayLink_Input & {ctx: UserContext }) => Promise GetLnurlWithdrawInfo?: (req: GetLnurlWithdrawInfo_Input & {ctx: GuestContext }) => Promise GetLnurlWithdrawLink?: (req: GetLnurlWithdrawLink_Input & {ctx: UserContext }) => Promise + GetManageAuthorizations?: (req: GetManageAuthorizations_Input & {ctx: UserContext }) => Promise GetMigrationUpdate?: (req: GetMigrationUpdate_Input & {ctx: UserContext }) => Promise GetNPubLinkingState?: (req: GetNPubLinkingState_Input & {ctx: AppContext }) => Promise GetPaymentState?: (req: GetPaymentState_Input & {ctx: UserContext }) => Promise @@ -2011,6 +2023,29 @@ export const LiveDebitRequestValidate = (o?: LiveDebitRequest, opts: LiveDebitRe return null } +export type LiveManageRequest = { + npub: string + request_id: string +} +export const LiveManageRequestOptionalFields: [] = [] +export type LiveManageRequestOptions = OptionsBaseMessage & { + checkOptionalsAreSet?: [] + npub_CustomCheck?: (v: string) => boolean + request_id_CustomCheck?: (v: string) => boolean +} +export const LiveManageRequestValidate = (o?: LiveManageRequest, opts: LiveManageRequestOptions = {}, path: string = 'LiveManageRequest::root.'): Error | null => { + if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message') + if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null') + + if (typeof o.npub !== 'string') return new Error(`${path}.npub: is not a string`) + if (opts.npub_CustomCheck && !opts.npub_CustomCheck(o.npub)) return new Error(`${path}.npub: custom check failed`) + + if (typeof o.request_id !== 'string') return new Error(`${path}.request_id: is not a string`) + if (opts.request_id_CustomCheck && !opts.request_id_CustomCheck(o.request_id)) return new Error(`${path}.request_id: custom check failed`) + + return null +} + export type LiveUserOperation = { operation: UserOperation } @@ -2470,6 +2505,86 @@ export const LnurlWithdrawInfoResponseValidate = (o?: LnurlWithdrawInfoResponse, return null } +export type ManageAuthorization = { + authorized: boolean + manage_id: string + npub: string +} +export const ManageAuthorizationOptionalFields: [] = [] +export type ManageAuthorizationOptions = OptionsBaseMessage & { + checkOptionalsAreSet?: [] + authorized_CustomCheck?: (v: boolean) => boolean + manage_id_CustomCheck?: (v: string) => boolean + npub_CustomCheck?: (v: string) => boolean +} +export const ManageAuthorizationValidate = (o?: ManageAuthorization, opts: ManageAuthorizationOptions = {}, path: string = 'ManageAuthorization::root.'): Error | null => { + if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message') + if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null') + + if (typeof o.authorized !== 'boolean') return new Error(`${path}.authorized: is not a boolean`) + if (opts.authorized_CustomCheck && !opts.authorized_CustomCheck(o.authorized)) return new Error(`${path}.authorized: custom check failed`) + + if (typeof o.manage_id !== 'string') return new Error(`${path}.manage_id: is not a string`) + if (opts.manage_id_CustomCheck && !opts.manage_id_CustomCheck(o.manage_id)) return new Error(`${path}.manage_id: custom check failed`) + + if (typeof o.npub !== 'string') return new Error(`${path}.npub: is not a string`) + if (opts.npub_CustomCheck && !opts.npub_CustomCheck(o.npub)) return new Error(`${path}.npub: custom check failed`) + + return null +} + +export type ManageAuthorizationRequest = { + authorize_npub: string + ban: boolean + request_id?: string +} +export type ManageAuthorizationRequestOptionalField = 'request_id' +export const ManageAuthorizationRequestOptionalFields: ManageAuthorizationRequestOptionalField[] = ['request_id'] +export type ManageAuthorizationRequestOptions = OptionsBaseMessage & { + checkOptionalsAreSet?: ManageAuthorizationRequestOptionalField[] + authorize_npub_CustomCheck?: (v: string) => boolean + ban_CustomCheck?: (v: boolean) => boolean + request_id_CustomCheck?: (v?: string) => boolean +} +export const ManageAuthorizationRequestValidate = (o?: ManageAuthorizationRequest, opts: ManageAuthorizationRequestOptions = {}, path: string = 'ManageAuthorizationRequest::root.'): Error | null => { + if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message') + if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null') + + if (typeof o.authorize_npub !== 'string') return new Error(`${path}.authorize_npub: is not a string`) + if (opts.authorize_npub_CustomCheck && !opts.authorize_npub_CustomCheck(o.authorize_npub)) return new Error(`${path}.authorize_npub: custom check failed`) + + if (typeof o.ban !== 'boolean') return new Error(`${path}.ban: is not a boolean`) + if (opts.ban_CustomCheck && !opts.ban_CustomCheck(o.ban)) return new Error(`${path}.ban: custom check failed`) + + if ((o.request_id || opts.allOptionalsAreSet || opts.checkOptionalsAreSet?.includes('request_id')) && typeof o.request_id !== 'string') return new Error(`${path}.request_id: is not a string`) + if (opts.request_id_CustomCheck && !opts.request_id_CustomCheck(o.request_id)) return new Error(`${path}.request_id: custom check failed`) + + return null +} + +export type ManageAuthorizations = { + manages: ManageAuthorization[] +} +export const ManageAuthorizationsOptionalFields: [] = [] +export type ManageAuthorizationsOptions = OptionsBaseMessage & { + checkOptionalsAreSet?: [] + manages_ItemOptions?: ManageAuthorizationOptions + manages_CustomCheck?: (v: ManageAuthorization[]) => boolean +} +export const ManageAuthorizationsValidate = (o?: ManageAuthorizations, opts: ManageAuthorizationsOptions = {}, path: string = 'ManageAuthorizations::root.'): Error | null => { + if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message') + if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null') + + if (!Array.isArray(o.manages)) return new Error(`${path}.manages: is not an array`) + for (let index = 0; index < o.manages.length; index++) { + const managesErr = ManageAuthorizationValidate(o.manages[index], opts.manages_ItemOptions, `${path}.manages[${index}]`) + if (managesErr !== null) return managesErr + } + if (opts.manages_CustomCheck && !opts.manages_CustomCheck(o.manages)) return new Error(`${path}.manages: custom check failed`) + + return null +} + export type MetricsFile = { } export const MetricsFileOptionalFields: [] = [] diff --git a/proto/service/methods.proto b/proto/service/methods.proto index 21f0a9d6..19f914da 100644 --- a/proto/service/methods.proto +++ b/proto/service/methods.proto @@ -592,12 +592,24 @@ service LightningPub { option (http_route) = "/api/user/debit/get"; option (nostr) = true; } + rpc GetManageAuthorizations(structs.Empty) returns (structs.ManageAuthorizations){ + option (auth_type) = "User"; + option (http_method) = "get"; + option (http_route) = "/api/user/manage/get"; + option (nostr) = true; + } rpc AuthorizeDebit(structs.DebitAuthorizationRequest) returns (structs.DebitAuthorization){ option (auth_type) = "User"; option (http_method) = "post"; option (http_route) = "/api/user/debit/authorize"; option (nostr) = true; } + rpc AuthorizeManage(structs.ManageAuthorizationRequest) returns (structs.ManageAuthorization){ + option (auth_type) = "User"; + option (http_method) = "post"; + option (http_route) = "/api/user/manage/authorize"; + option (nostr) = true; + } rpc EditDebit(structs.DebitAuthorizationRequest) returns (structs.Empty){ option (auth_type) = "User"; option (http_method) = "post"; @@ -628,6 +640,14 @@ service LightningPub { option (http_route) = "/api/user/debit/sub"; option (nostr) = true; } + + rpc GetLiveManageRequests(structs.Empty) returns (stream structs.LiveManageRequest){ + option (auth_type) = "User"; + option (http_method) = "post"; + option (http_route) = "/api/user/manage/sub"; + option (nostr) = true; + } + rpc GetLiveUserOperations(structs.Empty) returns (stream structs.LiveUserOperation){ option (auth_type) = "User"; option (http_method) = "post"; diff --git a/proto/service/structs.proto b/proto/service/structs.proto index 430198c5..3b1f0d8f 100644 --- a/proto/service/structs.proto +++ b/proto/service/structs.proto @@ -674,6 +674,22 @@ message DebitAuthorizationRequest { optional string request_id = 3; } +message ManageAuthorizationRequest { + string authorize_npub = 1; + optional string request_id = 2; + bool ban = 3; +} + +message ManageAuthorization { + string manage_id = 1; + bool authorized = 2; + string npub = 3; +} + +message ManageAuthorizations { + repeated ManageAuthorization manages = 1; +} + message DebitAuthorization { string debit_id = 1; bool authorized = 2; @@ -718,6 +734,11 @@ message LiveDebitRequest { } } +message LiveManageRequest { + string request_id = 1; + string npub = 2; +} + message DebitResponse { string request_id = 1; string npub = 2; diff --git a/src/services/main/managementManager.ts b/src/services/main/managementManager.ts index 26bf6b4d..2f31254e 100644 --- a/src/services/main/managementManager.ts +++ b/src/services/main/managementManager.ts @@ -7,14 +7,15 @@ import Storage from "../storage/index.js"; import { OfferManager } from "./offerManager.js"; import * as Types from "../../../proto/autogenerated/ts/types.js"; import { MainSettings } from "./settings.js"; -import { nofferEncode, OfferPointer, OfferPriceType, NmanageRequest, NmanageResponse, NmanageCreateOffer, NmanageUpdateOffer, NmanageDeleteOffer, NmanageGetOffer, NmanageListOffers, OfferData, OfferFields } from "@shocknet/clink-sdk"; +import { nofferEncode, OfferPointer, OfferPriceType, NmanageRequest, NmanageResponse, NmanageCreateOffer, NmanageUpdateOffer, NmanageDeleteOffer, NmanageGetOffer, NmanageListOffers, OfferData, OfferFields, NmanageFailure } from "@shocknet/clink-sdk"; import { UnsignedEvent } from "nostr-tools"; -type Result = { success: true, result: T } | { success: false, error: string, code: number } +type Result = { state: 'success', result: T } | { state: 'error', err: NmanageFailure } | { state: 'authRequired' } export class ManagementManager { private nostrSend: NostrSend; private storage: Storage; private settings: MainSettings; + private awaitingRequests: Record = {} constructor(storage: Storage, settings: MainSettings) { this.storage = storage; @@ -25,19 +26,62 @@ export class ManagementManager { this.nostrSend = f } - public async handleRequest(nmanageReq: NmanageRequest, event: NostrEvent): Promise { + AuthorizeManage = async (ctx: Types.UserContext, req: Types.ManageAuthorizationRequest): Promise => { + const grant = await this.storage.managementStorage.addGrant(ctx.app_user_id, req.authorize_npub, req.ban) + return { + manage_id: grant.serial_id.toString(), + authorized: !grant.banned, + npub: grant.app_pubkey, + } + } + + GetManageAuthorizations = async (ctx: Types.UserContext): Promise => { + const grants = await this.storage.managementStorage.getGrants(ctx.app_user_id) + return { + manages: grants.map(grant => ({ + manage_id: grant.serial_id.toString(), + authorized: !grant.banned, + npub: grant.app_pubkey, + })) + } + } + + private sendManageAuthorizationRequest = (appId: string, { requestId, npub }: { requestId: string, npub: string }) => { + const message: Types.LiveManageRequest & { requestId: string, status: 'OK' } = { requestId: "GetLiveManageRequests", status: 'OK', npub: npub, request_id: requestId } + this.nostrSend({ type: 'app', appId: appId }, { type: 'content', content: JSON.stringify(message), pub: npub }) + } + + private sendError(event: NostrEvent, err: NmanageFailure) { + const e = newNmanageResponse(JSON.stringify(err), event) + this.nostrSend({ type: 'app', appId: event.appId }, { type: 'event', event: e, encrypt: { toPub: event.pub } }) + } + + private handleAuthRequired(nmanageReq: NmanageRequest, event: NostrEvent) { + if (this.awaitingRequests[event.pub]) { + this.sendError(event, { res: 'GFY', code: 4, error: 'Rate Limited', retry_after: 60 * 10 }) + return + } + this.awaitingRequests[event.pub] = { request: nmanageReq, event } + this.sendManageAuthorizationRequest(event.appId, { requestId: event.id, npub: event.pub }) + } + + + + async handleRequest(nmanageReq: NmanageRequest, event: NostrEvent): Promise { try { const r = await this.doNmanage(nmanageReq, event) - let e: UnsignedEvent - if (!r.success) { - e = newNmanageResponse(JSON.stringify({ code: r.code, error: codeToMessage(r.code) }), event) - } else { - e = newNmanageResponse(JSON.stringify(r.result), event) + if (r.state === 'authRequired') { + this.handleAuthRequired(nmanageReq, event) + return } + if (r.state === 'error') { + this.sendError(event, r.err) + return + } + const e = newNmanageResponse(JSON.stringify(r.result), event) this.nostrSend({ type: 'app', appId: event.appId }, { type: 'event', event: e, encrypt: { toPub: event.pub } }) } catch (err) { - const e = newNmanageResponse(JSON.stringify({ code: 2, error: codeToMessage(2) }), event) - this.nostrSend({ type: 'app', appId: event.appId }, { type: 'event', event: e, encrypt: { toPub: event.pub } }) + this.sendError(event, { res: 'GFY', code: 2, error: 'Temporary Failure' }) } } @@ -60,7 +104,7 @@ export class ManagementManager { const listResult = await this.listOffers(nmanageReq, event.pub); return this.getNmanageResponse(event.appId, listResult) default: - return { success: false, error: `Unknown action: ${action}`, code: 1 } + return { state: 'error', err: { res: 'GFY', code: 1, error: `Request Denied: Unknown action: ${action}` } } } } @@ -83,23 +127,23 @@ export class ManagementManager { } private async getNmanageResponse(appId: string, result: Result): Promise> { - if (!result.success) { + if (result.state !== 'success') { return result } const args = result.result const app = await this.storage.applicationStorage.GetApplication(appId) if (args && Array.isArray(args)) { return { - success: true, result: { + state: 'success', result: { res: 'ok', resource: 'offer', details: args.map(offer => this.getOfferData(offer, app.nostr_public_key!)) } } } if (!args) { - return { success: true, result: { res: 'ok', resource: 'offer' } } + return { state: 'success', result: { res: 'ok', resource: 'offer' } } } return { - success: true, result: { + state: 'success', result: { res: 'ok', resource: 'offer', details: this.getOfferData(args, app.nostr_public_key!) } } @@ -107,53 +151,53 @@ export class ManagementManager { private async getOffer(nmanageReq: NmanageGetOffer, requestorPub: string): Promise> { const offer = await this.validateOfferAccess(nmanageReq.offer.id, requestorPub) - if (!offer.success) { + if (offer.state !== 'success') { return offer } - return { success: true, result: offer.result } + return { state: 'success', result: offer.result } } private async listOffers(nmanageReq: NmanageListOffers, requestorPub: string): Promise> { const appUserId = nmanageReq.pointer if (!appUserId) { - return { success: false, error: 'No pointer provided', code: 1 } + return { state: 'error', err: { res: 'GFY', code: 1, error: 'Request Denied: No pointer provided' } } } const grantResult = await this.validateGrantAccess(appUserId, requestorPub) - if (!grantResult.success) { + if (grantResult.state !== 'success') { return grantResult } const offers = await this.storage.offerStorage.getManagedUserOffers(appUserId, requestorPub) - return { success: true, result: offers } + return { state: 'success', result: offers } } private validateOfferFields(fields: OfferFields): Result { if (!fields.label || typeof fields.label !== 'string') { - return { success: false, error: 'Label is required', code: 1 } + return { state: 'error', err: { res: 'GFY', code: 5, error: 'Invalid Field/Value', field: 'label' } } } if (fields.price_sats && typeof fields.price_sats !== 'number') { - return { success: false, error: 'Price must be a number', code: 1 } + return { state: 'error', err: { res: 'GFY', code: 5, error: 'Invalid Field/Value', field: 'price_sats' } } } if (fields.callback_url && typeof fields.callback_url !== 'string') { - return { success: false, error: 'Callback URL must be a string', code: 1 } + return { state: 'error', err: { res: 'GFY', code: 5, error: 'Invalid Field/Value', field: 'callback_url' } } } if (fields.payer_data && !Array.isArray(fields.payer_data)) { - return { success: false, error: 'Payer data must be an array', code: 1 } + return { state: 'error', err: { res: 'GFY', code: 5, error: 'Invalid Field/Value', field: 'payer_data' } } } - return { success: true, result: undefined } + return { state: 'success', result: undefined } } private async createOffer(nmanageReq: NmanageCreateOffer): Promise> { const appUserId = nmanageReq.pointer if (!appUserId) { - return { success: false, error: 'No pointer provided', code: 1 } + return { state: 'error', err: { res: 'GFY', code: 1, error: 'Request Denied: No pointer provided' } } } const grantResult = await this.validateGrantAccess(appUserId, appUserId) - if (!grantResult.success) { + if (grantResult.state !== 'success') { return grantResult } const validateResult = this.validateOfferFields(nmanageReq.offer.fields) - if (!validateResult.success) { + if (validateResult.state !== 'success') { return validateResult } const dataMap: Record = {} @@ -166,51 +210,56 @@ export class ManagementManager { price_sats: nmanageReq.offer.fields.price_sats, expected_data: dataMap, }) - return { success: true, result: offer } + return { state: 'success', result: offer } } private async validateGrantAccess(appUserId: string, requestorPub: string): Promise> { const grant = await this.storage.managementStorage.getGrant(appUserId, requestorPub) if (!grant) { - // TODO request from user - return { success: false, error: 'No grant found', code: 1 } + return { state: 'authRequired' } } - if (grant.expires_at_unix < Date.now()) { - return { success: false, error: 'Grant expired', code: 3 } + if (grant.expires_at_unix > 0 && grant.expires_at_unix < Date.now()) { + return { state: 'authRequired' } } - return { success: true, result: undefined } + + if (grant.banned) { + return { state: 'error', err: { res: 'GFY', code: 1, error: 'Request Denied: App is banned' } } + } + + + return { state: 'success', result: undefined } } private async validateOfferAccess(offerId: string, requestorPub: string): Promise> { const offer = await this.storage.offerStorage.GetOffer(offerId) if (!offer) { - return { success: false, error: 'Offer not found', code: 1 } + return { state: 'error', err: { res: 'GFY', code: 1, error: 'Request Denied: Offer not found' } } } if (offer.management_pubkey !== requestorPub) { - return { success: false, error: 'App not authorized to update offer', code: 1 } + return { state: 'error', err: { res: 'GFY', code: 1, error: 'Request Denied: App not authorized to update offer' } } } const grantResult = await this.validateGrantAccess(offer.app_user_id, requestorPub) - if (!grantResult.success) { + if (grantResult.state !== 'success') { return grantResult } - return { success: true, result: offer } + return { state: 'success', result: offer } } private async updateOffer(nmanageReq: NmanageUpdateOffer, requestorPub: string): Promise> { const offer = await this.validateOfferAccess(nmanageReq.offer.id, requestorPub) - if (!offer.success) { + if (offer.state !== 'success') { return offer } const validateResult = this.validateOfferFields(nmanageReq.offer.fields) - if (!validateResult.success) { + if (validateResult.state !== 'success') { return validateResult } const dataMap: Record = {} for (const data of nmanageReq.offer.fields.payer_data || []) { if (typeof data !== 'string') { - return { success: false, error: 'Payer data must be a string', code: 1 } + return { state: 'error', err: { res: 'GFY', code: 5, error: 'Invalid Field/Value', field: 'payer_data' } } } dataMap[data] = Types.OfferDataType.DATA_STRING } @@ -222,18 +271,18 @@ export class ManagementManager { }) const updatedOffer = await this.storage.offerStorage.GetOffer(nmanageReq.offer.id) if (!updatedOffer) { - return { success: false, error: 'Offer not found', code: 2 } + return { state: 'error', err: { res: 'GFY', code: 2, error: 'Temporary Failure: Offer not found' } } } - return { success: true, result: updatedOffer } + return { state: 'success', result: updatedOffer } } private async deleteOffer(nmanageReq: NmanageDeleteOffer, requestorPub: string): Promise> { const offerResult = await this.validateOfferAccess(nmanageReq.offer.id, requestorPub) - if (!offerResult.success) { + if (offerResult.state !== 'success') { return offerResult } await this.storage.offerStorage.DeleteUserOffer(offerResult.result.app_user_id, offerResult.result.offer_id) - return { success: true, result: undefined } + return { state: 'success', result: undefined } } } diff --git a/src/services/serverMethods/index.ts b/src/services/serverMethods/index.ts index 5e204369..b33c2202 100644 --- a/src/services/serverMethods/index.ts +++ b/src/services/serverMethods/index.ts @@ -289,6 +289,7 @@ export default (mainHandler: Main): Types.ServerMethods => { await mainHandler.applicationManager.SetMockAppBalance(ctx.app_id, req) }, GetLiveDebitRequests: async ({ ctx }) => { }, + GetLiveManageRequests: async ({ ctx }) => { }, GetLiveUserOperations: async ({ ctx, cb }) => { }, GetMigrationUpdate: async ({ ctx, cb }) => { @@ -355,6 +356,12 @@ export default (mainHandler: Main): Types.ServerMethods => { GetDebitAuthorizations: async ({ ctx }) => { return mainHandler.debitManager.GetDebitAuthorizations(ctx) }, + AuthorizeManage: async ({ ctx, req }) => { + return mainHandler.managementManager.AuthorizeManage(ctx, req) + }, + GetManageAuthorizations: async ({ ctx }) => { + return mainHandler.managementManager.GetManageAuthorizations(ctx) + }, BanDebit: async ({ ctx, req }) => { const err = Types.DebitOperationValidate(req, { npub_CustomCheck: pub => pub !== '', diff --git a/src/services/storage/entity/ManagementGrant.ts b/src/services/storage/entity/ManagementGrant.ts index 46a962cd..1ce4650d 100644 --- a/src/services/storage/entity/ManagementGrant.ts +++ b/src/services/storage/entity/ManagementGrant.ts @@ -15,6 +15,9 @@ export class ManagementGrant { @Column() expires_at_unix: number + @Column() + banned: boolean + @CreateDateColumn() created_at: Date diff --git a/src/services/storage/managementStorage.ts b/src/services/storage/managementStorage.ts index 6ff5a8b0..092ecdd4 100644 --- a/src/services/storage/managementStorage.ts +++ b/src/services/storage/managementStorage.ts @@ -11,7 +11,11 @@ export class ManagementStorage { return this.dbs.FindOne('ManagementGrant', { where: { app_pubkey: appPubkey, app_user_id: appUserId } }); } - async addGrant(appUserId: string, appPubkey: string, expires_at_unix: number) { - return this.dbs.CreateAndSave('ManagementGrant', { app_user_id: appUserId, app_pubkey: appPubkey, expires_at_unix }); + async addGrant(appUserId: string, appPubkey: string, banned: boolean, expires_at_unix = 0) { + return this.dbs.CreateAndSave('ManagementGrant', { app_user_id: appUserId, app_pubkey: appPubkey, banned, expires_at_unix }); + } + + async getGrants(appUserId: string) { + return this.dbs.Find('ManagementGrant', { where: { app_user_id: appUserId } }); } } \ No newline at end of file diff --git a/src/services/storage/migrations/1751989251513-management_grant_banned.ts b/src/services/storage/migrations/1751989251513-management_grant_banned.ts new file mode 100644 index 00000000..511734a4 --- /dev/null +++ b/src/services/storage/migrations/1751989251513-management_grant_banned.ts @@ -0,0 +1,20 @@ +import { MigrationInterface, QueryRunner } from "typeorm"; + +export class ManagementGrantBanned1751989251513 implements MigrationInterface { + name = 'ManagementGrantBanned1751989251513' + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(`CREATE TABLE "temporary_management_grant" ("serial_id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "app_user_id" varchar NOT NULL, "app_pubkey" varchar NOT NULL, "expires_at_unix" integer NOT NULL, "created_at" datetime NOT NULL DEFAULT (datetime('now')), "updated_at" datetime NOT NULL DEFAULT (datetime('now')), "banned" boolean NOT NULL)`); + await queryRunner.query(`INSERT INTO "temporary_management_grant"("serial_id", "app_user_id", "app_pubkey", "expires_at_unix", "created_at", "updated_at") SELECT "serial_id", "app_user_id", "app_pubkey", "expires_at_unix", "created_at", "updated_at" FROM "management_grant"`); + await queryRunner.query(`DROP TABLE "management_grant"`); + await queryRunner.query(`ALTER TABLE "temporary_management_grant" RENAME TO "management_grant"`); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE "management_grant" RENAME TO "temporary_management_grant"`); + await queryRunner.query(`CREATE TABLE "management_grant" ("serial_id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "app_user_id" varchar NOT NULL, "app_pubkey" varchar NOT NULL, "expires_at_unix" integer NOT NULL, "created_at" datetime NOT NULL DEFAULT (datetime('now')), "updated_at" datetime NOT NULL DEFAULT (datetime('now')))`); + await queryRunner.query(`INSERT INTO "management_grant"("serial_id", "app_user_id", "app_pubkey", "expires_at_unix", "created_at", "updated_at") SELECT "serial_id", "app_user_id", "app_pubkey", "expires_at_unix", "created_at", "updated_at" FROM "temporary_management_grant"`); + await queryRunner.query(`DROP TABLE "temporary_management_grant"`); + } + +} From acfe5099e63f6af1a97b72413a27188619c148aa Mon Sep 17 00:00:00 2001 From: boufni95 Date: Tue, 8 Jul 2025 17:26:06 +0000 Subject: [PATCH 11/24] nmanage in user info --- package-lock.json | 8 ++++---- package.json | 2 +- proto/autogenerated/client.md | 1 + proto/autogenerated/go/types.go | 1 + proto/autogenerated/ts/types.ts | 5 +++++ proto/service/structs.proto | 1 + src/services/main/applicationManager.ts | 4 +++- 7 files changed, 16 insertions(+), 6 deletions(-) diff --git a/package-lock.json b/package-lock.json index a1f745cd..1c9a2b8d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,7 +13,7 @@ "@protobuf-ts/grpc-transport": "^2.9.4", "@protobuf-ts/plugin": "^2.5.0", "@protobuf-ts/runtime": "^2.5.0", - "@shocknet/clink-sdk": "^1.1.6", + "@shocknet/clink-sdk": "^1.1.7", "@stablelib/xchacha20": "^1.0.1", "@types/express": "^4.17.21", "@types/node": "^17.0.31", @@ -591,9 +591,9 @@ } }, "node_modules/@shocknet/clink-sdk": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/@shocknet/clink-sdk/-/clink-sdk-1.1.6.tgz", - "integrity": "sha512-PXNXdaS5sFIgfdWV5yMW0/ghrORAEVTy9K3fY4j/Rf4fjbNspBAaDioYn7to+lU/boPUxRMmFE0ix/2Mr6pkFQ==", + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/@shocknet/clink-sdk/-/clink-sdk-1.1.7.tgz", + "integrity": "sha512-9qr2WWalrPyi9ZoIsA2oEeQM3fWMCrVarghIStvkd/HoIR7oFjuHl+OUMLwvPxWXuCRIqnyRmXu970JVO8fx7Q==", "license": "ISC", "dependencies": { "@noble/hashes": "^1.8.0", diff --git a/package.json b/package.json index c3ea45d3..3ded2084 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,7 @@ "@protobuf-ts/grpc-transport": "^2.9.4", "@protobuf-ts/plugin": "^2.5.0", "@protobuf-ts/runtime": "^2.5.0", - "@shocknet/clink-sdk": "^1.1.6", + "@shocknet/clink-sdk": "^1.1.7", "@stablelib/xchacha20": "^1.0.1", "@types/express": "^4.17.21", "@types/node": "^17.0.31", diff --git a/proto/autogenerated/client.md b/proto/autogenerated/client.md index bacdf85c..659b7a25 100644 --- a/proto/autogenerated/client.md +++ b/proto/autogenerated/client.md @@ -1557,6 +1557,7 @@ The nostr server will send back a message response, and inside the body there wi - __ndebit__: _string_ - __network_max_fee_bps__: _number_ - __network_max_fee_fixed__: _number_ + - __nmanage__: _string_ - __noffer__: _string_ - __service_fee_bps__: _number_ - __userId__: _string_ diff --git a/proto/autogenerated/go/types.go b/proto/autogenerated/go/types.go index 4f797f59..151878c1 100644 --- a/proto/autogenerated/go/types.go +++ b/proto/autogenerated/go/types.go @@ -660,6 +660,7 @@ type UserInfo struct { Ndebit string `json:"ndebit"` Network_max_fee_bps int64 `json:"network_max_fee_bps"` Network_max_fee_fixed int64 `json:"network_max_fee_fixed"` + Nmanage string `json:"nmanage"` Noffer string `json:"noffer"` Service_fee_bps int64 `json:"service_fee_bps"` Userid string `json:"userId"` diff --git a/proto/autogenerated/ts/types.ts b/proto/autogenerated/ts/types.ts index 21d59051..937d8c5e 100644 --- a/proto/autogenerated/ts/types.ts +++ b/proto/autogenerated/ts/types.ts @@ -3795,6 +3795,7 @@ export type UserInfo = { ndebit: string network_max_fee_bps: number network_max_fee_fixed: number + nmanage: string noffer: string service_fee_bps: number userId: string @@ -3810,6 +3811,7 @@ export type UserInfoOptions = OptionsBaseMessage & { ndebit_CustomCheck?: (v: string) => boolean network_max_fee_bps_CustomCheck?: (v: number) => boolean network_max_fee_fixed_CustomCheck?: (v: number) => boolean + nmanage_CustomCheck?: (v: string) => boolean noffer_CustomCheck?: (v: string) => boolean service_fee_bps_CustomCheck?: (v: number) => boolean userId_CustomCheck?: (v: string) => boolean @@ -3840,6 +3842,9 @@ export const UserInfoValidate = (o?: UserInfo, opts: UserInfoOptions = {}, path: if (typeof o.network_max_fee_fixed !== 'number') return new Error(`${path}.network_max_fee_fixed: is not a number`) if (opts.network_max_fee_fixed_CustomCheck && !opts.network_max_fee_fixed_CustomCheck(o.network_max_fee_fixed)) return new Error(`${path}.network_max_fee_fixed: custom check failed`) + if (typeof o.nmanage !== 'string') return new Error(`${path}.nmanage: is not a string`) + if (opts.nmanage_CustomCheck && !opts.nmanage_CustomCheck(o.nmanage)) return new Error(`${path}.nmanage: custom check failed`) + if (typeof o.noffer !== 'string') return new Error(`${path}.noffer: is not a string`) if (opts.noffer_CustomCheck && !opts.noffer_CustomCheck(o.noffer)) return new Error(`${path}.noffer: custom check failed`) diff --git a/proto/service/structs.proto b/proto/service/structs.proto index 3b1f0d8f..6b587510 100644 --- a/proto/service/structs.proto +++ b/proto/service/structs.proto @@ -529,6 +529,7 @@ message UserInfo{ string ndebit = 9; string callback_url = 10; string bridge_url = 11; + string nmanage = 12; } message GetUserOperationsRequest{ int64 latestIncomingInvoice = 1; diff --git a/src/services/main/applicationManager.ts b/src/services/main/applicationManager.ts index df1f035a..d216f71c 100644 --- a/src/services/main/applicationManager.ts +++ b/src/services/main/applicationManager.ts @@ -9,7 +9,7 @@ import { PubLogger, getLogger } from '../helpers/logger.js' import crypto from 'crypto' import { Application } from '../storage/entity/Application.js' import { ZapInfo } from '../storage/entity/UserReceivingInvoice.js' -import { nofferEncode, ndebitEncode, OfferPriceType } from '@shocknet/clink-sdk' +import { nofferEncode, ndebitEncode, OfferPriceType, nmanageEncode } from '@shocknet/clink-sdk' const TOKEN_EXPIRY_TIME = 2 * 60 * 1000 // 2 minutes, in milliseconds type NsecLinkingData = { @@ -163,6 +163,7 @@ export default class { service_fee_bps: this.settings.outgoingAppUserInvoiceFeeBps, noffer: nofferEncode({ pubkey: app.nostr_public_key!, offer: u.identifier, priceType: OfferPriceType.Spontaneous, relay: nostrSettings.relays[0] }), ndebit: ndebitEncode({ pubkey: app.nostr_public_key!, pointer: u.identifier, relay: nostrSettings.relays[0] }), + nmanage: nmanageEncode({ pubkey: app.nostr_public_key!, pointer: u.identifier, relay: nostrSettings.relays[0] }), callback_url: u.callback_url, bridge_url: this.settings.bridgeUrl @@ -215,6 +216,7 @@ export default class { service_fee_bps: this.settings.outgoingAppUserInvoiceFeeBps, noffer: nofferEncode({ pubkey: app.nostr_public_key!, offer: user.identifier, priceType: OfferPriceType.Spontaneous, relay: nostrSettings.relays[0] }), ndebit: ndebitEncode({ pubkey: app.nostr_public_key!, pointer: user.identifier, relay: nostrSettings.relays[0] }), + nmanage: nmanageEncode({ pubkey: app.nostr_public_key!, pointer: user.identifier, relay: nostrSettings.relays[0] }), callback_url: user.callback_url, bridge_url: this.settings.bridgeUrl }, From d750db732d1dcba220a3d8273949227d77382ce5 Mon Sep 17 00:00:00 2001 From: boufni95 Date: Tue, 8 Jul 2025 17:26:51 +0000 Subject: [PATCH 12/24] up --- src/services/main/appUserManager.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/services/main/appUserManager.ts b/src/services/main/appUserManager.ts index 087197fb..12eae1f9 100644 --- a/src/services/main/appUserManager.ts +++ b/src/services/main/appUserManager.ts @@ -4,7 +4,7 @@ import * as Types from '../../../proto/autogenerated/ts/types.js' import { MainSettings } from './settings.js' import ApplicationManager from './applicationManager.js' -import { OfferPriceType, ndebitEncode, nofferEncode } from '@shocknet/clink-sdk' +import { OfferPriceType, ndebitEncode, nmanageEncode, nofferEncode } from '@shocknet/clink-sdk' export default class { storage: Storage @@ -76,6 +76,7 @@ export default class { service_fee_bps: this.settings.outgoingAppUserInvoiceFeeBps, noffer: nofferEncode({ pubkey: app.nostr_public_key!, offer: appUser.identifier, priceType: OfferPriceType.Spontaneous, relay: nostrSettings.relays[0] }), ndebit: ndebitEncode({ pubkey: app.nostr_public_key!, pointer: appUser.identifier, relay: nostrSettings.relays[0] }), + nmanage: nmanageEncode({ pubkey: app.nostr_public_key!, pointer: appUser.identifier, relay: nostrSettings.relays[0] }), callback_url: appUser.callback_url, bridge_url: this.settings.bridgeUrl } From 3afdb8bfd61ee9a3641734b0927900bf780f924f Mon Sep 17 00:00:00 2001 From: boufni95 Date: Tue, 8 Jul 2025 18:24:22 +0000 Subject: [PATCH 13/24] log err --- src/services/main/managementManager.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/services/main/managementManager.ts b/src/services/main/managementManager.ts index 2f31254e..304652cf 100644 --- a/src/services/main/managementManager.ts +++ b/src/services/main/managementManager.ts @@ -9,6 +9,8 @@ import * as Types from "../../../proto/autogenerated/ts/types.js"; import { MainSettings } from "./settings.js"; import { nofferEncode, OfferPointer, OfferPriceType, NmanageRequest, NmanageResponse, NmanageCreateOffer, NmanageUpdateOffer, NmanageDeleteOffer, NmanageGetOffer, NmanageListOffers, OfferData, OfferFields, NmanageFailure } from "@shocknet/clink-sdk"; import { UnsignedEvent } from "nostr-tools"; +import { getLogger, PubLogger } from "../helpers/logger.js"; +import { ERROR } from "sqlite3"; type Result = { state: 'success', result: T } | { state: 'error', err: NmanageFailure } | { state: 'authRequired' } export class ManagementManager { @@ -16,10 +18,11 @@ export class ManagementManager { private storage: Storage; private settings: MainSettings; private awaitingRequests: Record = {} - + private logger: PubLogger constructor(storage: Storage, settings: MainSettings) { this.storage = storage; this.settings = settings; + this.logger = getLogger({ component: 'ManagementManager' }) } attachNostrSend(f: NostrSend) { @@ -80,7 +83,8 @@ export class ManagementManager { } const e = newNmanageResponse(JSON.stringify(r.result), event) this.nostrSend({ type: 'app', appId: event.appId }, { type: 'event', event: e, encrypt: { toPub: event.pub } }) - } catch (err) { + } catch (err: any) { + this.logger(ERROR, err.message || err) this.sendError(event, { res: 'GFY', code: 2, error: 'Temporary Failure' }) } } From 9345f3c6cf32d7cf1683eb1539043f00679ebbc5 Mon Sep 17 00:00:00 2001 From: boufni95 Date: Tue, 8 Jul 2025 18:25:06 +0000 Subject: [PATCH 14/24] up --- src/services/main/managementManager.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/services/main/managementManager.ts b/src/services/main/managementManager.ts index 304652cf..c745aa59 100644 --- a/src/services/main/managementManager.ts +++ b/src/services/main/managementManager.ts @@ -9,8 +9,7 @@ import * as Types from "../../../proto/autogenerated/ts/types.js"; import { MainSettings } from "./settings.js"; import { nofferEncode, OfferPointer, OfferPriceType, NmanageRequest, NmanageResponse, NmanageCreateOffer, NmanageUpdateOffer, NmanageDeleteOffer, NmanageGetOffer, NmanageListOffers, OfferData, OfferFields, NmanageFailure } from "@shocknet/clink-sdk"; import { UnsignedEvent } from "nostr-tools"; -import { getLogger, PubLogger } from "../helpers/logger.js"; -import { ERROR } from "sqlite3"; +import { getLogger, PubLogger, ERROR } from "../helpers/logger.js"; type Result = { state: 'success', result: T } | { state: 'error', err: NmanageFailure } | { state: 'authRequired' } export class ManagementManager { From 399a25ee029e53ec7eb7b75bd00d1727fadcd3e1 Mon Sep 17 00:00:00 2001 From: boufni95 Date: Tue, 8 Jul 2025 18:26:31 +0000 Subject: [PATCH 15/24] up --- src/services/storage/migrations/runner.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/services/storage/migrations/runner.ts b/src/services/storage/migrations/runner.ts index 5217cc98..36e84a5a 100644 --- a/src/services/storage/migrations/runner.ts +++ b/src/services/storage/migrations/runner.ts @@ -18,7 +18,10 @@ import { UserOffer1733502626042 } from './1733502626042-user_offer.js' import { RootOpsTime1745428134124 } from './1745428134124-root_ops_time.js' import { ChannelEvents1750777346411 } from './1750777346411-channel_events.js' import { ManagementGrant1751307732346 } from './1751307732346-management_grant.js' -export const allMigrations = [Initial1703170309875, LspOrder1718387847693, LiquidityProvider1719335699480, LndNodeInfo1720187506189, TrackedProvider1720814323679, CreateInviteTokenTable1721751414878, PaymentIndex1721760297610, DebitAccess1726496225078, DebitAccessFixes1726685229264, DebitToPub1727105758354, UserCbUrl1727112281043, UserOffer1733502626042, ManagementGrant1751307732346] +import { ManagementGrantBanned1751989251513 } from './1751989251513-management_grant_banned.js' +export const allMigrations = [Initial1703170309875, LspOrder1718387847693, LiquidityProvider1719335699480, LndNodeInfo1720187506189, + TrackedProvider1720814323679, CreateInviteTokenTable1721751414878, PaymentIndex1721760297610, DebitAccess1726496225078, DebitAccessFixes1726685229264, + DebitToPub1727105758354, UserCbUrl1727112281043, UserOffer1733502626042, ManagementGrant1751307732346, ManagementGrantBanned1751989251513] export const allMetricsMigrations = [LndMetrics1703170330183, ChannelRouting1709316653538, HtlcCount1724266887195, BalanceEvents1724860966825, RootOps1732566440447, RootOpsTime1745428134124, ChannelEvents1750777346411] /* export const TypeOrmMigrationRunner = async (log: PubLogger, storageManager: Storage, settings: DbSettings, arg: string | undefined): Promise => { await connectAndMigrate(log, storageManager, allMigrations, allMetricsMigrations) From ff47eae1ba37a3e6cc570f46e962f5ac6d35aa7b Mon Sep 17 00:00:00 2001 From: boufni95 Date: Tue, 8 Jul 2025 18:47:27 +0000 Subject: [PATCH 16/24] up --- src/services/main/managementManager.ts | 1 + src/services/main/watchdog.ts | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/services/main/managementManager.ts b/src/services/main/managementManager.ts index c745aa59..e49eb161 100644 --- a/src/services/main/managementManager.ts +++ b/src/services/main/managementManager.ts @@ -50,6 +50,7 @@ export class ManagementManager { private sendManageAuthorizationRequest = (appId: string, { requestId, npub }: { requestId: string, npub: string }) => { const message: Types.LiveManageRequest & { requestId: string, status: 'OK' } = { requestId: "GetLiveManageRequests", status: 'OK', npub: npub, request_id: requestId } + this.logger("Sending manage authorization request to", npub, "for app", appId) this.nostrSend({ type: 'app', appId: appId }, { type: 'content', content: JSON.stringify(message), pub: npub }) } diff --git a/src/services/main/watchdog.ts b/src/services/main/watchdog.ts index b5ffed51..07e59662 100644 --- a/src/services/main/watchdog.ts +++ b/src/services/main/watchdog.ts @@ -78,7 +78,7 @@ export class Watchdog { const knownMaxIndex = paymentFound.length > 0 ? Math.max(paymentFound[0].paymentIndex, 0) : 0 this.latestPaymentIndexOffset = await this.lnd.GetLatestPaymentIndex(knownMaxIndex) const other = { ilnd: this.initialLndBalance, hf: this.accumulatedHtlcFees, iu: this.initialUsersBalance, tu: totalUsersBalance, oext: otherExternal } - getLogger({ component: 'watchdog_debug2' })(JSON.stringify({ deltaLnd: 0, deltaUsers: 0, totalExternal, latestIndex: this.latestPaymentIndexOffset, other })) + //getLogger({ component: 'watchdog_debug2' })(JSON.stringify({ deltaLnd: 0, deltaUsers: 0, totalExternal, latestIndex: this.latestPaymentIndexOffset, other })) this.interval = setInterval(() => { if (this.latestCheckStart + (1000 * 58) < Date.now()) { this.PaymentRequested() @@ -192,7 +192,7 @@ export class Watchdog { const newLatest = await this.lnd.GetLatestPaymentIndex(knownMaxIndex) const historyMismatch = newLatest > knownMaxIndex const other = { ilnd: this.initialLndBalance, hf: this.accumulatedHtlcFees, iu: this.initialUsersBalance, tu: totalUsersBalance, km: knownMaxIndex, nl: newLatest, oext: otherExternal } - getLogger({ component: 'watchdog_debug2' })(JSON.stringify({ deltaLnd, deltaUsers, totalExternal, other })) + //getLogger({ component: 'watchdog_debug2' })(JSON.stringify({ deltaLnd, deltaUsers, totalExternal, other })) const deny = await this.checkBalanceUpdate(deltaLnd, deltaUsers) if (historyMismatch) { getLogger({ component: 'bark' })("History mismatch detected in absolute update, locking outgoing operations") From 6af226bbc39435bd6d05eb59eb9d2438f75aaf10 Mon Sep 17 00:00:00 2001 From: boufni95 Date: Tue, 8 Jul 2025 19:05:29 +0000 Subject: [PATCH 17/24] pub fix --- src/services/main/managementManager.ts | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/services/main/managementManager.ts b/src/services/main/managementManager.ts index e49eb161..cd69db32 100644 --- a/src/services/main/managementManager.ts +++ b/src/services/main/managementManager.ts @@ -48,10 +48,10 @@ export class ManagementManager { } } - private sendManageAuthorizationRequest = (appId: string, { requestId, npub }: { requestId: string, npub: string }) => { + private sendManageAuthorizationRequest = (appId: string, userPub: string, { requestId, npub }: { requestId: string, npub: string }) => { const message: Types.LiveManageRequest & { requestId: string, status: 'OK' } = { requestId: "GetLiveManageRequests", status: 'OK', npub: npub, request_id: requestId } this.logger("Sending manage authorization request to", npub, "for app", appId) - this.nostrSend({ type: 'app', appId: appId }, { type: 'content', content: JSON.stringify(message), pub: npub }) + this.nostrSend({ type: 'app', appId: appId }, { type: 'content', content: JSON.stringify(message), pub: userPub }) } private sendError(event: NostrEvent, err: NmanageFailure) { @@ -59,13 +59,13 @@ export class ManagementManager { this.nostrSend({ type: 'app', appId: event.appId }, { type: 'event', event: e, encrypt: { toPub: event.pub } }) } - private handleAuthRequired(nmanageReq: NmanageRequest, event: NostrEvent) { + private handleAuthRequired(nmanageReq: NmanageRequest, event: NostrEvent, userPub: string) { if (this.awaitingRequests[event.pub]) { this.sendError(event, { res: 'GFY', code: 4, error: 'Rate Limited', retry_after: 60 * 10 }) return } this.awaitingRequests[event.pub] = { request: nmanageReq, event } - this.sendManageAuthorizationRequest(event.appId, { requestId: event.id, npub: event.pub }) + this.sendManageAuthorizationRequest(event.appId, userPub, { requestId: event.id, npub: event.pub }) } @@ -74,10 +74,18 @@ export class ManagementManager { try { const r = await this.doNmanage(nmanageReq, event) if (r.state === 'authRequired') { - this.handleAuthRequired(nmanageReq, event) + const app = await this.storage.applicationStorage.GetApplication(event.appId) + const appUser = await this.storage.applicationStorage.GetApplicationUser(app, event.pub) + if (!appUser.nostr_public_key) { + this.logger(ERROR, "App user has no nostr public key", event.pub) + this.sendError(event, { res: 'GFY', code: 1, error: 'Request Denied: App user has no nostr public key' }) + return + } + this.handleAuthRequired(nmanageReq, event, appUser.nostr_public_key) return } if (r.state === 'error') { + this.logger(ERROR, "Error in nmanage request", r.err) this.sendError(event, r.err) return } From de28b5ce3c20e228ea35acfba92529e3d4265f55 Mon Sep 17 00:00:00 2001 From: boufni95 Date: Tue, 8 Jul 2025 19:27:09 +0000 Subject: [PATCH 18/24] fix --- src/services/main/managementManager.ts | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/src/services/main/managementManager.ts b/src/services/main/managementManager.ts index cd69db32..edcb3fb1 100644 --- a/src/services/main/managementManager.ts +++ b/src/services/main/managementManager.ts @@ -59,13 +59,26 @@ export class ManagementManager { this.nostrSend({ type: 'app', appId: event.appId }, { type: 'event', event: e, encrypt: { toPub: event.pub } }) } - private handleAuthRequired(nmanageReq: NmanageRequest, event: NostrEvent, userPub: string) { + private async handleAuthRequired(nmanageReq: NmanageRequest, event: NostrEvent) { if (this.awaitingRequests[event.pub]) { this.sendError(event, { res: 'GFY', code: 4, error: 'Rate Limited', retry_after: 60 * 10 }) return } + const appUserId = (nmanageReq as { pointer?: string }).pointer + if (!appUserId) { + this.logger(ERROR, "No pointer provided", event.pub) + this.sendError(event, { res: 'GFY', code: 1, error: 'Request Denied: No pointer provided, cannot sent auth request' }) + return + } + const app = await this.storage.applicationStorage.GetApplication(event.appId) + const appUser = await this.storage.applicationStorage.GetApplicationUser(app, appUserId) + if (!appUser.nostr_public_key) { + this.logger(ERROR, "App user has no nostr public key", event.pub) + this.sendError(event, { res: 'GFY', code: 1, error: 'Request Denied: App user has no nostr public key' }) + return + } this.awaitingRequests[event.pub] = { request: nmanageReq, event } - this.sendManageAuthorizationRequest(event.appId, userPub, { requestId: event.id, npub: event.pub }) + this.sendManageAuthorizationRequest(event.appId, appUser.nostr_public_key, { requestId: event.id, npub: event.pub }) } @@ -74,14 +87,7 @@ export class ManagementManager { try { const r = await this.doNmanage(nmanageReq, event) if (r.state === 'authRequired') { - const app = await this.storage.applicationStorage.GetApplication(event.appId) - const appUser = await this.storage.applicationStorage.GetApplicationUser(app, event.pub) - if (!appUser.nostr_public_key) { - this.logger(ERROR, "App user has no nostr public key", event.pub) - this.sendError(event, { res: 'GFY', code: 1, error: 'Request Denied: App user has no nostr public key' }) - return - } - this.handleAuthRequired(nmanageReq, event, appUser.nostr_public_key) + await this.handleAuthRequired(nmanageReq, event) return } if (r.state === 'error') { From 33ad95c9bdf5594e0f24b9fbff9f46d455f0c60a Mon Sep 17 00:00:00 2001 From: boufni95 Date: Tue, 8 Jul 2025 19:30:52 +0000 Subject: [PATCH 19/24] complete req after auth --- src/services/main/managementManager.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/services/main/managementManager.ts b/src/services/main/managementManager.ts index edcb3fb1..767259b3 100644 --- a/src/services/main/managementManager.ts +++ b/src/services/main/managementManager.ts @@ -30,6 +30,11 @@ export class ManagementManager { AuthorizeManage = async (ctx: Types.UserContext, req: Types.ManageAuthorizationRequest): Promise => { const grant = await this.storage.managementStorage.addGrant(ctx.app_user_id, req.authorize_npub, req.ban) + const awaiting = this.awaitingRequests[req.authorize_npub] + if (awaiting) { + delete this.awaitingRequests[req.authorize_npub] + await this.handleRequest(awaiting.request, awaiting.event) + } return { manage_id: grant.serial_id.toString(), authorized: !grant.banned, From 2cc02b35c528da4ffc1a95796888cedaea947ffe Mon Sep 17 00:00:00 2001 From: boufni95 Date: Tue, 8 Jul 2025 19:31:22 +0000 Subject: [PATCH 20/24] fix --- src/services/main/managementManager.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/services/main/managementManager.ts b/src/services/main/managementManager.ts index 767259b3..ef702d09 100644 --- a/src/services/main/managementManager.ts +++ b/src/services/main/managementManager.ts @@ -33,7 +33,9 @@ export class ManagementManager { const awaiting = this.awaitingRequests[req.authorize_npub] if (awaiting) { delete this.awaitingRequests[req.authorize_npub] - await this.handleRequest(awaiting.request, awaiting.event) + if (!grant.banned) { + await this.handleRequest(awaiting.request, awaiting.event) + } } return { manage_id: grant.serial_id.toString(), From 6abed0e4485bbfe1cef151c68a3f09cc983256ec Mon Sep 17 00:00:00 2001 From: boufni95 Date: Tue, 8 Jul 2025 20:00:43 +0000 Subject: [PATCH 21/24] deb --- src/services/main/managementManager.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/services/main/managementManager.ts b/src/services/main/managementManager.ts index ef702d09..8b20b509 100644 --- a/src/services/main/managementManager.ts +++ b/src/services/main/managementManager.ts @@ -242,10 +242,12 @@ export class ManagementManager { const grant = await this.storage.managementStorage.getGrant(appUserId, requestorPub) if (!grant) { + this.logger(ERROR, "No grant found", appUserId, requestorPub) return { state: 'authRequired' } } if (grant.expires_at_unix > 0 && grant.expires_at_unix < Date.now()) { + this.logger(ERROR, "Grant expired", appUserId, requestorPub) return { state: 'authRequired' } } From 96ad06597895e45a513359f6419aec7973c36531 Mon Sep 17 00:00:00 2001 From: boufni95 Date: Tue, 8 Jul 2025 20:03:01 +0000 Subject: [PATCH 22/24] fix --- src/services/main/managementManager.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/services/main/managementManager.ts b/src/services/main/managementManager.ts index 8b20b509..ffcff9b5 100644 --- a/src/services/main/managementManager.ts +++ b/src/services/main/managementManager.ts @@ -114,7 +114,7 @@ export class ManagementManager { const action = nmanageReq.action switch (action) { case "create": - const createResult = await this.createOffer(nmanageReq) + const createResult = await this.createOffer(nmanageReq, event.pub) return this.getNmanageResponse(event.appId, createResult) case "update": const updateResult = await this.updateOffer(nmanageReq, event.pub); @@ -212,12 +212,12 @@ export class ManagementManager { return { state: 'success', result: undefined } } - private async createOffer(nmanageReq: NmanageCreateOffer): Promise> { + private async createOffer(nmanageReq: NmanageCreateOffer, requestorPub: string): Promise> { const appUserId = nmanageReq.pointer if (!appUserId) { return { state: 'error', err: { res: 'GFY', code: 1, error: 'Request Denied: No pointer provided' } } } - const grantResult = await this.validateGrantAccess(appUserId, appUserId) + const grantResult = await this.validateGrantAccess(appUserId, requestorPub) if (grantResult.state !== 'success') { return grantResult } From 70001b287cc0ffdf7cad473455a994b8adb39f4e Mon Sep 17 00:00:00 2001 From: boufni95 Date: Tue, 8 Jul 2025 20:05:51 +0000 Subject: [PATCH 23/24] list fix --- src/services/main/managementManager.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/services/main/managementManager.ts b/src/services/main/managementManager.ts index ffcff9b5..b958c469 100644 --- a/src/services/main/managementManager.ts +++ b/src/services/main/managementManager.ts @@ -234,6 +234,7 @@ export class ManagementManager { callback_url: nmanageReq.offer.fields.callback_url, price_sats: nmanageReq.offer.fields.price_sats, expected_data: dataMap, + management_pubkey: requestorPub, }) return { state: 'success', result: offer } } From 7a0013527b5d5d96b0790a02454ecd550d8e2916 Mon Sep 17 00:00:00 2001 From: boufni95 Date: Wed, 9 Jul 2025 15:37:13 +0000 Subject: [PATCH 24/24] grant reset --- proto/autogenerated/client.md | 15 ++++++++++ proto/autogenerated/go/http_client.go | 25 +++++++++++++++++ proto/autogenerated/go/types.go | 3 ++ proto/autogenerated/ts/express_server.ts | 34 +++++++++++++++++++++++ proto/autogenerated/ts/http_client.ts | 11 ++++++++ proto/autogenerated/ts/nostr_client.ts | 12 ++++++++ proto/autogenerated/ts/nostr_transport.ts | 28 +++++++++++++++++++ proto/autogenerated/ts/types.ts | 26 +++++++++++++++-- proto/service/methods.proto | 18 ++++++++---- proto/service/structs.proto | 4 +++ src/services/main/managementManager.ts | 4 +++ src/services/serverMethods/index.ts | 7 +++++ src/services/storage/managementStorage.ts | 4 +++ 13 files changed, 183 insertions(+), 8 deletions(-) diff --git a/proto/autogenerated/client.md b/proto/autogenerated/client.md index 659b7a25..0f871cd6 100644 --- a/proto/autogenerated/client.md +++ b/proto/autogenerated/client.md @@ -285,6 +285,11 @@ The nostr server will send back a message response, and inside the body there wi - input: [DebitOperation](#DebitOperation) - This methods has an __empty__ __response__ body +- ResetManage + - auth type: __User__ + - input: [ManageOperation](#ManageOperation) + - This methods has an __empty__ __response__ body + - ResetMetricsStorages - auth type: __Metrics__ - This methods has an __empty__ __request__ body @@ -876,6 +881,13 @@ The nostr server will send back a message response, and inside the body there wi - input: [DebitOperation](#DebitOperation) - This methods has an __empty__ __response__ body +- ResetManage + - auth type: __User__ + - http method: __post__ + - http route: __/api/user/manage/reset__ + - input: [ManageOperation](#ManageOperation) + - This methods has an __empty__ __response__ body + - ResetMetricsStorages - auth type: __Metrics__ - http method: __post__ @@ -1343,6 +1355,9 @@ The nostr server will send back a message response, and inside the body there wi ### ManageAuthorizations - __manages__: ARRAY of: _[ManageAuthorization](#ManageAuthorization)_ +### ManageOperation + - __npub__: _string_ + ### MetricsFile ### MigrationUpdate diff --git a/proto/autogenerated/go/http_client.go b/proto/autogenerated/go/http_client.go index 3971791f..7e64e7c8 100644 --- a/proto/autogenerated/go/http_client.go +++ b/proto/autogenerated/go/http_client.go @@ -124,6 +124,7 @@ type Client struct { PingSubProcesses func() error RequestNPubLinkingToken func(req RequestNPubLinkingTokenRequest) (*RequestNPubLinkingTokenResponse, error) ResetDebit func(req DebitOperation) error + ResetManage func(req ManageOperation) error ResetMetricsStorages func() error ResetNPubLinkingToken func(req RequestNPubLinkingTokenRequest) (*RequestNPubLinkingTokenResponse, error) RespondToDebit func(req DebitResponse) error @@ -1913,6 +1914,30 @@ func NewClient(params ClientParams) *Client { } return nil }, + ResetManage: func(req ManageOperation) error { + auth, err := params.RetrieveUserAuth() + if err != nil { + return err + } + finalRoute := "/api/user/manage/reset" + body, err := json.Marshal(req) + if err != nil { + return err + } + resBody, err := doPostRequest(params.BaseURL+finalRoute, body, auth) + if err != nil { + return err + } + result := ResultError{} + err = json.Unmarshal(resBody, &result) + if err != nil { + return err + } + if result.Status == "ERROR" { + return fmt.Errorf(result.Reason) + } + return nil + }, ResetMetricsStorages: func() error { auth, err := params.RetrieveMetricsAuth() if err != nil { diff --git a/proto/autogenerated/go/types.go b/proto/autogenerated/go/types.go index 151878c1..f718dccf 100644 --- a/proto/autogenerated/go/types.go +++ b/proto/autogenerated/go/types.go @@ -446,6 +446,9 @@ type ManageAuthorizationRequest struct { type ManageAuthorizations struct { Manages []ManageAuthorization `json:"manages"` } +type ManageOperation struct { + Npub string `json:"npub"` +} type MetricsFile struct { } type MigrationUpdate struct { diff --git a/proto/autogenerated/ts/express_server.ts b/proto/autogenerated/ts/express_server.ts index b7b4a73f..26ac2294 100644 --- a/proto/autogenerated/ts/express_server.ts +++ b/proto/autogenerated/ts/express_server.ts @@ -625,6 +625,18 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => { callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) } break + case 'ResetManage': + if (!methods.ResetManage) { + throw new Error('method ResetManage not found' ) + } else { + const error = Types.ManageOperationValidate(operation.req) + opStats.validate = process.hrtime.bigint() + if (error !== null) throw error + await methods.ResetManage({...operation, ctx}); responses.push({ status: 'OK' }) + opStats.handle = process.hrtime.bigint() + callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) + } + break case 'RespondToDebit': if (!methods.RespondToDebit) { throw new Error('method RespondToDebit not found' ) @@ -1784,6 +1796,28 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => { opts.metricsCallback([{ ...info, ...stats, ...authContext }]) } catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } }) + if (!opts.allowNotImplementedMethods && !methods.ResetManage) throw new Error('method: ResetManage is not implemented') + app.post('/api/user/manage/reset', async (req, res) => { + const info: Types.RequestInfo = { rpcName: 'ResetManage', batch: false, nostr: false, batchSize: 0} + const stats: Types.RequestStats = { startMs:req.startTimeMs || 0, start:req.startTime || 0n, parse: process.hrtime.bigint(), guard: 0n, validate: 0n, handle: 0n } + let authCtx: Types.AuthContext = {} + try { + if (!methods.ResetManage) throw new Error('method: ResetManage is not implemented') + const authContext = await opts.UserAuthGuard(req.headers['authorization']) + authCtx = authContext + stats.guard = process.hrtime.bigint() + const request = req.body + const error = Types.ManageOperationValidate(request) + stats.validate = process.hrtime.bigint() + if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback) + const query = req.query + const params = req.params + await methods.ResetManage({rpcName:'ResetManage', ctx:authContext , req: request}) + stats.handle = process.hrtime.bigint() + res.json({status: 'OK'}) + opts.metricsCallback([{ ...info, ...stats, ...authContext }]) + } catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } + }) if (!opts.allowNotImplementedMethods && !methods.ResetMetricsStorages) throw new Error('method: ResetMetricsStorages is not implemented') app.post('/api/metrics/reset', async (req, res) => { const info: Types.RequestInfo = { rpcName: 'ResetMetricsStorages', batch: false, nostr: false, batchSize: 0} diff --git a/proto/autogenerated/ts/http_client.ts b/proto/autogenerated/ts/http_client.ts index 615265f4..038d91ad 100644 --- a/proto/autogenerated/ts/http_client.ts +++ b/proto/autogenerated/ts/http_client.ts @@ -920,6 +920,17 @@ export default (params: ClientParams) => ({ } return { status: 'ERROR', reason: 'invalid response' } }, + ResetManage: async (request: Types.ManageOperation): Promise => { + const auth = await params.retrieveUserAuth() + if (auth === null) throw new Error('retrieveUserAuth() returned null') + let finalRoute = '/api/user/manage/reset' + const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } }) + if (data.status === 'ERROR' && typeof data.reason === 'string') return data + if (data.status === 'OK') { + return data + } + return { status: 'ERROR', reason: 'invalid response' } + }, ResetMetricsStorages: async (): Promise => { const auth = await params.retrieveMetricsAuth() if (auth === null) throw new Error('retrieveMetricsAuth() returned null') diff --git a/proto/autogenerated/ts/nostr_client.ts b/proto/autogenerated/ts/nostr_client.ts index 569c5842..f06e4eee 100644 --- a/proto/autogenerated/ts/nostr_client.ts +++ b/proto/autogenerated/ts/nostr_client.ts @@ -781,6 +781,18 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ } return { status: 'ERROR', reason: 'invalid response' } }, + ResetManage: async (request: Types.ManageOperation): Promise => { + const auth = await params.retrieveNostrUserAuth() + if (auth === null) throw new Error('retrieveNostrUserAuth() returned null') + const nostrRequest: NostrRequest = {} + nostrRequest.body = request + const data = await send(params.pubDestination, {rpcName:'ResetManage',authIdentifier:auth, ...nostrRequest }) + if (data.status === 'ERROR' && typeof data.reason === 'string') return data + if (data.status === 'OK') { + return data + } + return { status: 'ERROR', reason: 'invalid response' } + }, ResetMetricsStorages: async (): Promise => { const auth = await params.retrieveNostrMetricsAuth() if (auth === null) throw new Error('retrieveNostrMetricsAuth() returned null') diff --git a/proto/autogenerated/ts/nostr_transport.ts b/proto/autogenerated/ts/nostr_transport.ts index e7e93016..dc244600 100644 --- a/proto/autogenerated/ts/nostr_transport.ts +++ b/proto/autogenerated/ts/nostr_transport.ts @@ -501,6 +501,18 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => { callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) } break + case 'ResetManage': + if (!methods.ResetManage) { + throw new Error('method not defined: ResetManage') + } else { + const error = Types.ManageOperationValidate(operation.req) + opStats.validate = process.hrtime.bigint() + if (error !== null) throw error + await methods.ResetManage({...operation, ctx}); responses.push({ status: 'OK' }) + opStats.handle = process.hrtime.bigint() + callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) + } + break case 'RespondToDebit': if (!methods.RespondToDebit) { throw new Error('method not defined: RespondToDebit') @@ -1207,6 +1219,22 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => { opts.metricsCallback([{ ...info, ...stats, ...authContext }]) }catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } break + case 'ResetManage': + try { + if (!methods.ResetManage) throw new Error('method: ResetManage is not implemented') + const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier) + stats.guard = process.hrtime.bigint() + authCtx = authContext + const request = req.body + const error = Types.ManageOperationValidate(request) + stats.validate = process.hrtime.bigint() + if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback) + await methods.ResetManage({rpcName:'ResetManage', ctx:authContext , req: request}) + stats.handle = process.hrtime.bigint() + res({status: 'OK'}) + opts.metricsCallback([{ ...info, ...stats, ...authContext }]) + }catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } + break case 'ResetMetricsStorages': try { if (!methods.ResetMetricsStorages) throw new Error('method: ResetMetricsStorages is not implemented') diff --git a/proto/autogenerated/ts/types.ts b/proto/autogenerated/ts/types.ts index 937d8c5e..06af2539 100644 --- a/proto/autogenerated/ts/types.ts +++ b/proto/autogenerated/ts/types.ts @@ -35,8 +35,8 @@ export type UserContext = { app_user_id: string user_id: string } -export type UserMethodInputs = AddProduct_Input | AddUserOffer_Input | AuthorizeDebit_Input | AuthorizeManage_Input | BanDebit_Input | DecodeInvoice_Input | DeleteUserOffer_Input | EditDebit_Input | EnrollAdminToken_Input | GetDebitAuthorizations_Input | GetHttpCreds_Input | GetLNURLChannelLink_Input | GetLnurlPayLink_Input | GetLnurlWithdrawLink_Input | GetManageAuthorizations_Input | GetPaymentState_Input | GetUserInfo_Input | GetUserOffer_Input | GetUserOfferInvoices_Input | GetUserOffers_Input | GetUserOperations_Input | NewAddress_Input | NewInvoice_Input | NewProductInvoice_Input | PayAddress_Input | PayInvoice_Input | ResetDebit_Input | RespondToDebit_Input | UpdateCallbackUrl_Input | UpdateUserOffer_Input | UserHealth_Input -export type UserMethodOutputs = AddProduct_Output | AddUserOffer_Output | AuthorizeDebit_Output | AuthorizeManage_Output | BanDebit_Output | DecodeInvoice_Output | DeleteUserOffer_Output | EditDebit_Output | EnrollAdminToken_Output | GetDebitAuthorizations_Output | GetHttpCreds_Output | GetLNURLChannelLink_Output | GetLnurlPayLink_Output | GetLnurlWithdrawLink_Output | GetManageAuthorizations_Output | GetPaymentState_Output | GetUserInfo_Output | GetUserOffer_Output | GetUserOfferInvoices_Output | GetUserOffers_Output | GetUserOperations_Output | NewAddress_Output | NewInvoice_Output | NewProductInvoice_Output | PayAddress_Output | PayInvoice_Output | ResetDebit_Output | RespondToDebit_Output | UpdateCallbackUrl_Output | UpdateUserOffer_Output | UserHealth_Output +export type UserMethodInputs = AddProduct_Input | AddUserOffer_Input | AuthorizeDebit_Input | AuthorizeManage_Input | BanDebit_Input | DecodeInvoice_Input | DeleteUserOffer_Input | EditDebit_Input | EnrollAdminToken_Input | GetDebitAuthorizations_Input | GetHttpCreds_Input | GetLNURLChannelLink_Input | GetLnurlPayLink_Input | GetLnurlWithdrawLink_Input | GetManageAuthorizations_Input | GetPaymentState_Input | GetUserInfo_Input | GetUserOffer_Input | GetUserOfferInvoices_Input | GetUserOffers_Input | GetUserOperations_Input | NewAddress_Input | NewInvoice_Input | NewProductInvoice_Input | PayAddress_Input | PayInvoice_Input | ResetDebit_Input | ResetManage_Input | RespondToDebit_Input | UpdateCallbackUrl_Input | UpdateUserOffer_Input | UserHealth_Input +export type UserMethodOutputs = AddProduct_Output | AddUserOffer_Output | AuthorizeDebit_Output | AuthorizeManage_Output | BanDebit_Output | DecodeInvoice_Output | DeleteUserOffer_Output | EditDebit_Output | EnrollAdminToken_Output | GetDebitAuthorizations_Output | GetHttpCreds_Output | GetLNURLChannelLink_Output | GetLnurlPayLink_Output | GetLnurlWithdrawLink_Output | GetManageAuthorizations_Output | GetPaymentState_Output | GetUserInfo_Output | GetUserOffer_Output | GetUserOfferInvoices_Output | GetUserOffers_Output | GetUserOperations_Output | NewAddress_Output | NewInvoice_Output | NewProductInvoice_Output | PayAddress_Output | PayInvoice_Output | ResetDebit_Output | ResetManage_Output | RespondToDebit_Output | UpdateCallbackUrl_Output | UpdateUserOffer_Output | UserHealth_Output export type AuthContext = AdminContext | AppContext | GuestContext | GuestWithPubContext | MetricsContext | UserContext export type AddApp_Input = {rpcName:'AddApp', req: AddAppRequest} @@ -271,6 +271,9 @@ export type RequestNPubLinkingToken_Output = ResultError | ({ status: 'OK' } & R export type ResetDebit_Input = {rpcName:'ResetDebit', req: DebitOperation} export type ResetDebit_Output = ResultError | { status: 'OK' } +export type ResetManage_Input = {rpcName:'ResetManage', req: ManageOperation} +export type ResetManage_Output = ResultError | { status: 'OK' } + export type ResetMetricsStorages_Input = {rpcName:'ResetMetricsStorages'} export type ResetMetricsStorages_Output = ResultError | { status: 'OK' } @@ -389,6 +392,7 @@ export type ServerMethods = { PingSubProcesses?: (req: PingSubProcesses_Input & {ctx: MetricsContext }) => Promise RequestNPubLinkingToken?: (req: RequestNPubLinkingToken_Input & {ctx: AppContext }) => Promise ResetDebit?: (req: ResetDebit_Input & {ctx: UserContext }) => Promise + ResetManage?: (req: ResetManage_Input & {ctx: UserContext }) => Promise ResetMetricsStorages?: (req: ResetMetricsStorages_Input & {ctx: MetricsContext }) => Promise ResetNPubLinkingToken?: (req: ResetNPubLinkingToken_Input & {ctx: AppContext }) => Promise RespondToDebit?: (req: RespondToDebit_Input & {ctx: UserContext }) => Promise @@ -2585,6 +2589,24 @@ export const ManageAuthorizationsValidate = (o?: ManageAuthorizations, opts: Man return null } +export type ManageOperation = { + npub: string +} +export const ManageOperationOptionalFields: [] = [] +export type ManageOperationOptions = OptionsBaseMessage & { + checkOptionalsAreSet?: [] + npub_CustomCheck?: (v: string) => boolean +} +export const ManageOperationValidate = (o?: ManageOperation, opts: ManageOperationOptions = {}, path: string = 'ManageOperation::root.'): Error | null => { + if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message') + if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null') + + if (typeof o.npub !== 'string') return new Error(`${path}.npub: is not a string`) + if (opts.npub_CustomCheck && !opts.npub_CustomCheck(o.npub)) return new Error(`${path}.npub: custom check failed`) + + return null +} + export type MetricsFile = { } export const MetricsFileOptionalFields: [] = [] diff --git a/proto/service/methods.proto b/proto/service/methods.proto index 19f914da..b20bdb73 100644 --- a/proto/service/methods.proto +++ b/proto/service/methods.proto @@ -598,18 +598,24 @@ service LightningPub { option (http_route) = "/api/user/manage/get"; option (nostr) = true; } - rpc AuthorizeDebit(structs.DebitAuthorizationRequest) returns (structs.DebitAuthorization){ - option (auth_type) = "User"; - option (http_method) = "post"; - option (http_route) = "/api/user/debit/authorize"; - option (nostr) = true; - } rpc AuthorizeManage(structs.ManageAuthorizationRequest) returns (structs.ManageAuthorization){ option (auth_type) = "User"; option (http_method) = "post"; option (http_route) = "/api/user/manage/authorize"; option (nostr) = true; } + rpc ResetManage(structs.ManageOperation) returns (structs.Empty){ + option (auth_type) = "User"; + option (http_method) = "post"; + option (http_route) = "/api/user/manage/reset"; + option (nostr) = true; + } + rpc AuthorizeDebit(structs.DebitAuthorizationRequest) returns (structs.DebitAuthorization){ + option (auth_type) = "User"; + option (http_method) = "post"; + option (http_route) = "/api/user/debit/authorize"; + option (nostr) = true; + } rpc EditDebit(structs.DebitAuthorizationRequest) returns (structs.Empty){ option (auth_type) = "User"; option (http_method) = "post"; diff --git a/proto/service/structs.proto b/proto/service/structs.proto index 6b587510..43bb75ad 100644 --- a/proto/service/structs.proto +++ b/proto/service/structs.proto @@ -675,6 +675,10 @@ message DebitAuthorizationRequest { optional string request_id = 3; } +message ManageOperation { + string npub = 1; +} + message ManageAuthorizationRequest { string authorize_npub = 1; optional string request_id = 2; diff --git a/src/services/main/managementManager.ts b/src/services/main/managementManager.ts index b958c469..ce3f255e 100644 --- a/src/services/main/managementManager.ts +++ b/src/services/main/managementManager.ts @@ -28,6 +28,10 @@ export class ManagementManager { this.nostrSend = f } + ResetManage = async (ctx: Types.UserContext, req: Types.ManageOperation): Promise => { + await this.storage.managementStorage.removeGrant(ctx.app_user_id, req.npub) + } + AuthorizeManage = async (ctx: Types.UserContext, req: Types.ManageAuthorizationRequest): Promise => { const grant = await this.storage.managementStorage.addGrant(ctx.app_user_id, req.authorize_npub, req.ban) const awaiting = this.awaitingRequests[req.authorize_npub] diff --git a/src/services/serverMethods/index.ts b/src/services/serverMethods/index.ts index b33c2202..653eadb9 100644 --- a/src/services/serverMethods/index.ts +++ b/src/services/serverMethods/index.ts @@ -362,6 +362,13 @@ export default (mainHandler: Main): Types.ServerMethods => { GetManageAuthorizations: async ({ ctx }) => { return mainHandler.managementManager.GetManageAuthorizations(ctx) }, + ResetManage: async ({ ctx, req }) => { + const err = Types.ManageOperationValidate(req, { + npub_CustomCheck: pub => pub !== '', + }) + if (err != null) throw new Error(err.message) + return mainHandler.managementManager.ResetManage(ctx, req) + }, BanDebit: async ({ ctx, req }) => { const err = Types.DebitOperationValidate(req, { npub_CustomCheck: pub => pub !== '', diff --git a/src/services/storage/managementStorage.ts b/src/services/storage/managementStorage.ts index 092ecdd4..1cc263b5 100644 --- a/src/services/storage/managementStorage.ts +++ b/src/services/storage/managementStorage.ts @@ -18,4 +18,8 @@ export class ManagementStorage { async getGrants(appUserId: string) { return this.dbs.Find('ManagementGrant', { where: { app_user_id: appUserId } }); } + + async removeGrant(appUserId: string, appPubkey: string) { + return this.dbs.Delete('ManagementGrant', { app_pubkey: appPubkey, app_user_id: appUserId }); + } } \ No newline at end of file