diff --git a/CLAUDE.md b/CLAUDE.md index 25fa6ed9..3b5769a5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -221,6 +221,23 @@ Bennu still has them, and a Bennu member can put one to a group Giza is in, so: `./gradlew check` runs `docs/scripts/wallet-audit.sh --check`, which fails on a retired kind in the app's code, a lightning-kmp import, a file named for a wallet's pieces, or sats in a string. +## Everything sent in a NIP-17 wrap expires + +[docs/disappearing-messages.md](docs/disappearing-messages.md). What a person writes expires +after their policy, a day by default; a protocol round expires after the longer of that and its +protocol's floor, and always does. The rumor's `expiration` is part of its id, so a producer of a +`GiftWrapPayload` stamps it before hashing: + +```kotlin +val tags = DisappearingSettingsStore(database).stamp(chatRoomId, userPublicKey, kind, createdAt, baseTags) // yes +val id = EventHasher.hashId(userPublicKey, createdAt, kind, tags, content) +``` + +A new kind gets a class in `DisappearingMessages.classOf`, with the reason for its floor; +`DisappearingMessagesTest` fails on a kind the app sends that fell through to the unclassified +week. A session that reads its rounds back from `GiftWrapPayload` answers in `ProtocolRetention`, +or the sweeper will delete them once they expire. Seals stay untagged. + ## Checking your work ```bash diff --git a/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/50.json b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/50.json new file mode 100644 index 00000000..c1717007 --- /dev/null +++ b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/50.json @@ -0,0 +1,7487 @@ +{ + "formatVersion": 1, + "database": { + "version": 50, + "identityHash": "d4864b1d217e8bd4e7d7168749a03b80", + "entities": [ + { + "tableName": "BroadcastNostrEventReceipt", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `nostrEventId` TEXT NOT NULL, `unsignedNostrEventId` INTEGER, `isAccepted` INTEGER NOT NULL, `isSync` INTEGER NOT NULL, `relayURL` TEXT NOT NULL, `messages` TEXT, FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "isAccepted", + "columnName": "isAccepted", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isSync", + "columnName": "isSync", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "messages", + "columnName": "messages", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_BroadcastNostrEventReceipt_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventReceipt_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_BroadcastNostrEventReceipt_isAccepted", + "unique": false, + "columnNames": [ + "isAccepted" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventReceipt_isAccepted` ON `${TABLE_NAME}` (`isAccepted`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UnsignedNostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "unsignedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "BroadcastNostrEventRequest", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `nostrEventId` TEXT NOT NULL, `unsignedNostrEventId` INTEGER, `status` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_BroadcastNostrEventRequest_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventRequest_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_BroadcastNostrEventRequest_status", + "unique": false, + "columnNames": [ + "status" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventRequest_status` ON `${TABLE_NAME}` (`status`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UnsignedNostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "unsignedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Connection", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sourcePublicKey` TEXT NOT NULL, `destinationPublicKey` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`sourcePublicKey`, `destinationPublicKey`), FOREIGN KEY(`sourcePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`destinationPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sourcePublicKey", + "columnName": "sourcePublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "destinationPublicKey", + "columnName": "destinationPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sourcePublicKey", + "destinationPublicKey" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sourcePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "destinationPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + } + ] + }, + { + "tableName": "ChatMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `senderPublicKey` TEXT NOT NULL, `isUserMessage` INTEGER NOT NULL, `giftWrapPayloadId` TEXT, `marmotGroupEventId` TEXT, `marmotInnerEventId` TEXT, `chatRoomId` TEXT NOT NULL, `replyToMessageId` INTEGER, `quotedMessageId` INTEGER, `content` TEXT NOT NULL, `messageType` TEXT NOT NULL, `directMessageRecipientPublicKey` TEXT, `expiresAt` INTEGER, `frostSigningSessionId` TEXT, `dkgSessionId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`giftWrapPayloadId`) REFERENCES `GiftWrapPayload`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`marmotGroupEventId`) REFERENCES `MarmotGroupEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`marmotInnerEventId`) REFERENCES `MarmotInnerEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isUserMessage", + "columnName": "isUserMessage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "giftWrapPayloadId", + "columnName": "giftWrapPayloadId", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotInnerEventId", + "columnName": "marmotInnerEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "replyToMessageId", + "columnName": "replyToMessageId", + "affinity": "INTEGER" + }, + { + "fieldPath": "quotedMessageId", + "columnName": "quotedMessageId", + "affinity": "INTEGER" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "messageType", + "columnName": "messageType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "directMessageRecipientPublicKey", + "columnName": "directMessageRecipientPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "expiresAt", + "columnName": "expiresAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "frostSigningSessionId", + "columnName": "frostSigningSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ChatMessage_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ChatMessage_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_ChatMessage_expiresAt", + "unique": false, + "columnNames": [ + "expiresAt" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ChatMessage_expiresAt` ON `${TABLE_NAME}` (`expiresAt`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "GiftWrapPayload", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapPayloadId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "MarmotGroupEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "marmotGroupEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "MarmotInnerEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "marmotInnerEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageBroadcastNostrEventRequestRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `broadcastNostrEventRequestId` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`broadcastNostrEventRequestId`) REFERENCES `BroadcastNostrEventRequest`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "broadcastNostrEventRequestId", + "columnName": "broadcastNostrEventRequestId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "BroadcastNostrEventRequest", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "broadcastNostrEventRequestId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageBroadcastNostrEventReceiptRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `broadcastNostrEventReceiptId` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`broadcastNostrEventReceiptId`) REFERENCES `BroadcastNostrEventReceipt`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "broadcastNostrEventReceiptId", + "columnName": "broadcastNostrEventReceiptId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "BroadcastNostrEventReceipt", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "broadcastNostrEventReceiptId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageNostrEventRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatRoom", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `subject` TEXT, `description` TEXT, `mlsGroupState` TEXT, `initialGiftWrapPayloadId` TEXT, `leftGroupAt` INTEGER, `joinedGroupAt` INTEGER, `chronicleRequestedAt` INTEGER, `parentChatRoomId` TEXT, `lastReadMessageId` INTEGER, `notifications` TEXT NOT NULL DEFAULT 'all', `disappearingMessageSecs` INTEGER, `disappearingNoticeShownAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`userPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`initialGiftWrapPayloadId`) REFERENCES `GiftWrapPayload`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT" + }, + { + "fieldPath": "description", + "columnName": "description", + "affinity": "TEXT" + }, + { + "fieldPath": "mlsGroupState", + "columnName": "mlsGroupState", + "affinity": "TEXT" + }, + { + "fieldPath": "initialGiftWrapPayloadId", + "columnName": "initialGiftWrapPayloadId", + "affinity": "TEXT" + }, + { + "fieldPath": "leftGroupAt", + "columnName": "leftGroupAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "joinedGroupAt", + "columnName": "joinedGroupAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "chronicleRequestedAt", + "columnName": "chronicleRequestedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "parentChatRoomId", + "columnName": "parentChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "lastReadMessageId", + "columnName": "lastReadMessageId", + "affinity": "INTEGER" + }, + { + "fieldPath": "notifications", + "columnName": "notifications", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "'all'" + }, + { + "fieldPath": "disappearingMessageSecs", + "columnName": "disappearingMessageSecs", + "affinity": "INTEGER" + }, + { + "fieldPath": "disappearingNoticeShownAt", + "columnName": "disappearingNoticeShownAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "userPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "GiftWrapPayload", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "initialGiftWrapPayloadId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Confederation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `ceremonyId` TEXT NOT NULL, `name` TEXT NOT NULL, `roster` TEXT NOT NULL, `keyState` TEXT NOT NULL, `genesis` TEXT NOT NULL, `configSeq` INTEGER NOT NULL, `rosterHash` TEXT NOT NULL, `keyStateHash` TEXT NOT NULL, `recoveryPackages` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `roomCreator` TEXT, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "proposalId", + "columnName": "proposalId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ceremonyId", + "columnName": "ceremonyId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "roster", + "columnName": "roster", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "keyState", + "columnName": "keyState", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "genesis", + "columnName": "genesis", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "configSeq", + "columnName": "configSeq", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "rosterHash", + "columnName": "rosterHash", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "keyStateHash", + "columnName": "keyStateHash", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "recoveryPackages", + "columnName": "recoveryPackages", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "roomCreator", + "columnName": "roomCreator", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Confederation_proposalId", + "unique": false, + "columnNames": [ + "proposalId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Confederation_proposalId` ON `${TABLE_NAME}` (`proposalId`)" + } + ] + }, + { + "tableName": "DisappearingSetting", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`userPublicKey` TEXT NOT NULL, `defaultSeconds` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`userPublicKey`))", + "fields": [ + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "defaultSeconds", + "columnName": "defaultSeconds", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "userPublicKey" + ] + } + }, + { + "tableName": "ExpiredGiftWrap", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `dropAfter` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dropAfter", + "columnName": "dropAfter", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + } + }, + { + "tableName": "ConfederationCeremony", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `basisJson` TEXT NOT NULL, `attempt` INTEGER NOT NULL DEFAULT 1, `attestationRef` TEXT, `seedContribution` TEXT, `stage` TEXT NOT NULL, `approvedAt` INTEGER, `dealerSeeds` TEXT, `recoveryNonces` TEXT, `keyState` TEXT, `transitionHash` TEXT, `genesis` TEXT, `recoveryPackages` TEXT, `confederationPublicKey` TEXT, `failureReason` TEXT, `culprit` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "proposalId", + "columnName": "proposalId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "basisJson", + "columnName": "basisJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "attempt", + "columnName": "attempt", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "1" + }, + { + "fieldPath": "attestationRef", + "columnName": "attestationRef", + "affinity": "TEXT" + }, + { + "fieldPath": "seedContribution", + "columnName": "seedContribution", + "affinity": "TEXT" + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "approvedAt", + "columnName": "approvedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "dealerSeeds", + "columnName": "dealerSeeds", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryNonces", + "columnName": "recoveryNonces", + "affinity": "TEXT" + }, + { + "fieldPath": "keyState", + "columnName": "keyState", + "affinity": "TEXT" + }, + { + "fieldPath": "transitionHash", + "columnName": "transitionHash", + "affinity": "TEXT" + }, + { + "fieldPath": "genesis", + "columnName": "genesis", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryPackages", + "columnName": "recoveryPackages", + "affinity": "TEXT" + }, + { + "fieldPath": "confederationPublicKey", + "columnName": "confederationPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "culprit", + "columnName": "culprit", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ConfederationCeremony_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationCeremony_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_ConfederationCeremony_proposalId", + "unique": false, + "columnNames": [ + "proposalId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationCeremony_proposalId` ON `${TABLE_NAME}` (`proposalId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ConfederationMember", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`confederationId` TEXT NOT NULL, `groupPublicKey` TEXT NOT NULL, PRIMARY KEY(`confederationId`, `groupPublicKey`))", + "fields": [ + { + "fieldPath": "confederationId", + "columnName": "confederationId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "groupPublicKey", + "columnName": "groupPublicKey", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "confederationId", + "groupPublicKey" + ] + }, + "indices": [ + { + "name": "index_ConfederationMember_groupPublicKey", + "unique": false, + "columnNames": [ + "groupPublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationMember_groupPublicKey` ON `${TABLE_NAME}` (`groupPublicKey`)" + } + ] + }, + { + "tableName": "ConfederationSigningAttempt", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `confederationId` TEXT NOT NULL, `proposerPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `eventJson` TEXT NOT NULL, `stage` TEXT NOT NULL, `approvedAt` INTEGER, `declinedAt` INTEGER, `signedEventJson` TEXT, `failureReason` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`confederationId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "confederationId", + "columnName": "confederationId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "proposerPublicKey", + "columnName": "proposerPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "eventJson", + "columnName": "eventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "approvedAt", + "columnName": "approvedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "declinedAt", + "columnName": "declinedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "signedEventJson", + "columnName": "signedEventJson", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ConfederationSigningAttempt_confederationId", + "unique": false, + "columnNames": [ + "confederationId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationSigningAttempt_confederationId` ON `${TABLE_NAME}` (`confederationId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "confederationId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ConfederationSigningMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`attemptId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`attemptId`, `senderPublicKey`, `kind`), FOREIGN KEY(`attemptId`) REFERENCES `ConfederationSigningAttempt`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "attemptId", + "columnName": "attemptId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "attemptId", + "senderPublicKey", + "kind" + ] + }, + "foreignKeys": [ + { + "table": "ConfederationSigningAttempt", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "attemptId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ConfederationCeremonyMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `senderPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `ConfederationCeremony`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "senderPublicKey", + "kind" + ] + }, + "foreignKeys": [ + { + "table": "ConfederationCeremony", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ConfederationEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `kind` INTEGER NOT NULL, `pubKey` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `eventCreatedAt` INTEGER NOT NULL, `eventJson` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, `ownSessionId` TEXT, `publishedAt` INTEGER, `sealJson` TEXT, `inboxRoomId` TEXT, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "pubKey", + "columnName": "pubKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "proposalId", + "columnName": "proposalId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "eventCreatedAt", + "columnName": "eventCreatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "eventJson", + "columnName": "eventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "ownSessionId", + "columnName": "ownSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "publishedAt", + "columnName": "publishedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "sealJson", + "columnName": "sealJson", + "affinity": "TEXT" + }, + { + "fieldPath": "inboxRoomId", + "columnName": "inboxRoomId", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ConfederationEvent_proposalId", + "unique": false, + "columnNames": [ + "proposalId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_proposalId` ON `${TABLE_NAME}` (`proposalId`)" + }, + { + "name": "index_ConfederationEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_kind` ON `${TABLE_NAME}` (`kind`)" + }, + { + "name": "index_ConfederationEvent_publishedAt", + "unique": false, + "columnNames": [ + "publishedAt" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_publishedAt` ON `${TABLE_NAME}` (`publishedAt`)" + } + ] + }, + { + "tableName": "ConfederationInvitee", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`proposalId` TEXT NOT NULL, `groupPublicKey` TEXT NOT NULL, PRIMARY KEY(`proposalId`, `groupPublicKey`))", + "fields": [ + { + "fieldPath": "proposalId", + "columnName": "proposalId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "groupPublicKey", + "columnName": "groupPublicKey", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "proposalId", + "groupPublicKey" + ] + }, + "indices": [ + { + "name": "index_ConfederationInvitee_groupPublicKey", + "unique": false, + "columnNames": [ + "groupPublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationInvitee_groupPublicKey` ON `${TABLE_NAME}` (`groupPublicKey`)" + } + ] + }, + { + "tableName": "ConfederationSigning", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `rumorJson` TEXT, `invitationJson` TEXT, `refusal` TEXT, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`), FOREIGN KEY(`sessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "rumorJson", + "columnName": "rumorJson", + "affinity": "TEXT" + }, + { + "fieldPath": "invitationJson", + "columnName": "invitationJson", + "affinity": "TEXT" + }, + { + "fieldPath": "refusal", + "columnName": "refusal", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId" + ] + }, + "foreignKeys": [ + { + "table": "FrostSigningSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "DkgParticipantMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `participantPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `participantPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `DkgSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participantPublicKey", + "columnName": "participantPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "participantPublicKey", + "kind" + ] + }, + "indices": [ + { + "name": "index_DkgParticipantMessage_sessionId", + "unique": false, + "columnNames": [ + "sessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_DkgParticipantMessage_sessionId` ON `${TABLE_NAME}` (`sessionId`)" + } + ], + "foreignKeys": [ + { + "table": "DkgSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "DkgSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `threshold` INTEGER NOT NULL, `participantCount` INTEGER NOT NULL, `participantPublicKeys` TEXT, `subject` TEXT, `walletPolicy` TEXT, `stage` TEXT NOT NULL, `hostPublicKey` TEXT NOT NULL, `round1Random` TEXT NOT NULL, `round2AuxRandom` TEXT NOT NULL, `coordinatorRound1` TEXT, `certificate` TEXT, `thresholdPublicKey` TEXT, `secretShare` TEXT, `publicShares` TEXT, `recoveryData` TEXT, `failureReason` TEXT, `hostKeyApprovedAt` INTEGER, `round1ApprovedAt` INTEGER, `round2ApprovedAt` INTEGER, `approvalRequestedThrough` TEXT, `parentChatRoomId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "threshold", + "columnName": "threshold", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantCount", + "columnName": "participantCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantPublicKeys", + "columnName": "participantPublicKeys", + "affinity": "TEXT" + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT" + }, + { + "fieldPath": "walletPolicy", + "columnName": "walletPolicy", + "affinity": "TEXT" + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "hostPublicKey", + "columnName": "hostPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "round1Random", + "columnName": "round1Random", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "round2AuxRandom", + "columnName": "round2AuxRandom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorRound1", + "columnName": "coordinatorRound1", + "affinity": "TEXT" + }, + { + "fieldPath": "certificate", + "columnName": "certificate", + "affinity": "TEXT" + }, + { + "fieldPath": "thresholdPublicKey", + "columnName": "thresholdPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "secretShare", + "columnName": "secretShare", + "affinity": "TEXT" + }, + { + "fieldPath": "publicShares", + "columnName": "publicShares", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryData", + "columnName": "recoveryData", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "hostKeyApprovedAt", + "columnName": "hostKeyApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "round1ApprovedAt", + "columnName": "round1ApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "round2ApprovedAt", + "columnName": "round2ApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequestedThrough", + "columnName": "approvalRequestedThrough", + "affinity": "TEXT" + }, + { + "fieldPath": "parentChatRoomId", + "columnName": "parentChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_DkgSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_DkgSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "FrostSignerMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `signerPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `signerPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signerPublicKey", + "columnName": "signerPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "signerPublicKey", + "kind" + ] + }, + "indices": [ + { + "name": "index_FrostSignerMessage_sessionId", + "unique": false, + "columnNames": [ + "sessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSignerMessage_sessionId` ON `${TABLE_NAME}` (`sessionId`)" + } + ], + "foreignKeys": [ + { + "table": "FrostSigningSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "FrostSigningItem", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `itemIndex` INTEGER NOT NULL, `unsignedEventJson` TEXT NOT NULL, `eventId` TEXT NOT NULL, `nonceRandom` TEXT NOT NULL, `aggregatedNonce` TEXT, `signature` TEXT, PRIMARY KEY(`sessionId`, `itemIndex`), FOREIGN KEY(`sessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "itemIndex", + "columnName": "itemIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "unsignedEventJson", + "columnName": "unsignedEventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "eventId", + "columnName": "eventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nonceRandom", + "columnName": "nonceRandom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "aggregatedNonce", + "columnName": "aggregatedNonce", + "affinity": "TEXT" + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "itemIndex" + ] + }, + "indices": [ + { + "name": "index_FrostSigningItem_sessionId", + "unique": false, + "columnNames": [ + "sessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningItem_sessionId` ON `${TABLE_NAME}` (`sessionId`)" + } + ], + "foreignKeys": [ + { + "table": "FrostSigningSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "FrostSigningSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `threshold` INTEGER NOT NULL, `participantCount` INTEGER NOT NULL, `signerId` INTEGER NOT NULL, `derivationPath` TEXT, `generation` INTEGER, `stage` TEXT NOT NULL, `signerIds` TEXT, `failureReason` TEXT, `signApprovedAt` INTEGER, `signDeclinedAt` INTEGER, `approvalRequestedAt` INTEGER, `resentAt` INTEGER, `subject` TEXT NOT NULL DEFAULT 'EVENTS', `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "threshold", + "columnName": "threshold", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantCount", + "columnName": "participantCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "signerId", + "columnName": "signerId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT" + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER" + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signerIds", + "columnName": "signerIds", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "signApprovedAt", + "columnName": "signApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "signDeclinedAt", + "columnName": "signDeclinedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequestedAt", + "columnName": "approvalRequestedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "resentAt", + "columnName": "resentAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "'EVENTS'" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_FrostSigningSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_FrostSigningSession_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningSession_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `receiverPublicKey` TEXT NOT NULL, `receiverRelayHit` TEXT, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `giftWrapPayloadId` TEXT, `expiresAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "receiverPublicKey", + "columnName": "receiverPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receiverRelayHit", + "columnName": "receiverRelayHit", + "affinity": "TEXT" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "giftWrapPayloadId", + "columnName": "giftWrapPayloadId", + "affinity": "TEXT" + }, + { + "fieldPath": "expiresAt", + "columnName": "expiresAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GiftWrapMessage_giftWrapPayloadId", + "unique": false, + "columnNames": [ + "giftWrapPayloadId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GiftWrapMessage_giftWrapPayloadId` ON `${TABLE_NAME}` (`giftWrapPayloadId`)" + }, + { + "name": "index_GiftWrapMessage_expiresAt", + "unique": false, + "columnNames": [ + "expiresAt" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GiftWrapMessage_expiresAt` ON `${TABLE_NAME}` (`expiresAt`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapSeal", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `giftWrapMessageId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`giftWrapMessageId`) REFERENCES `GiftWrapMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "giftWrapMessageId", + "columnName": "giftWrapMessageId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "GiftWrapMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapMessageId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapPayload", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `quotedEventId` TEXT, `giftWrapSealId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `expiresAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`giftWrapSealId`) REFERENCES `GiftWrapSeal`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedEventId", + "columnName": "quotedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "giftWrapSealId", + "columnName": "giftWrapSealId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "expiresAt", + "columnName": "expiresAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GiftWrapPayload_expiresAt", + "unique": false, + "columnNames": [ + "expiresAt" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GiftWrapPayload_expiresAt` ON `${TABLE_NAME}` (`expiresAt`)" + } + ], + "foreignKeys": [ + { + "table": "GiftWrapSeal", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapSealId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupConversationKey", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `peer` TEXT NOT NULL, `conversationKey` TEXT NOT NULL, `roundId` TEXT NOT NULL, `computedAt` INTEGER NOT NULL, PRIMARY KEY(`chatRoomId`, `peer`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "peer", + "columnName": "peer", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "conversationKey", + "columnName": "conversationKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "roundId", + "columnName": "roundId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "computedAt", + "columnName": "computedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId", + "peer" + ] + }, + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupDmMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`rumorId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `conversationId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `rumorJson` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `outgoing` INTEGER NOT NULL, `wrapId` TEXT, `signingSessionId` TEXT, `readAt` INTEGER, `filedAt` INTEGER NOT NULL, `expiresAt` INTEGER, PRIMARY KEY(`rumorId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "rumorId", + "columnName": "rumorId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "conversationId", + "columnName": "conversationId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "rumorJson", + "columnName": "rumorJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "outgoing", + "columnName": "outgoing", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "wrapId", + "columnName": "wrapId", + "affinity": "TEXT" + }, + { + "fieldPath": "signingSessionId", + "columnName": "signingSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "readAt", + "columnName": "readAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "filedAt", + "columnName": "filedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "expiresAt", + "columnName": "expiresAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "rumorId" + ] + }, + "indices": [ + { + "name": "index_GroupDmMessage_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupDmMessage_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupDmMessage_conversationId", + "unique": false, + "columnNames": [ + "conversationId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupDmMessage_conversationId` ON `${TABLE_NAME}` (`conversationId`)" + }, + { + "name": "index_GroupDmMessage_expiresAt", + "unique": false, + "columnNames": [ + "expiresAt" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupDmMessage_expiresAt` ON `${TABLE_NAME}` (`expiresAt`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupDmOutbound", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`signingSessionId` TEXT NOT NULL, `sealId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `recipient` TEXT NOT NULL, `relays` TEXT NOT NULL, `wrapJson` TEXT, `publishedAt` INTEGER, `attempts` INTEGER NOT NULL, `nextAttemptAt` INTEGER, PRIMARY KEY(`signingSessionId`, `sealId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "signingSessionId", + "columnName": "signingSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sealId", + "columnName": "sealId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "recipient", + "columnName": "recipient", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relays", + "columnName": "relays", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "wrapJson", + "columnName": "wrapJson", + "affinity": "TEXT" + }, + { + "fieldPath": "publishedAt", + "columnName": "publishedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "attempts", + "columnName": "attempts", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nextAttemptAt", + "columnName": "nextAttemptAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "signingSessionId", + "sealId" + ] + }, + "indices": [ + { + "name": "index_GroupDmOutbound_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupDmOutbound_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupDmWrap", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `wrapJson` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `state` TEXT NOT NULL, `sealJson` TEXT, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "wrapJson", + "columnName": "wrapJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "state", + "columnName": "state", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sealJson", + "columnName": "sealJson", + "affinity": "TEXT" + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GroupDmWrap_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupDmWrap_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupDmWrap_state", + "unique": false, + "columnNames": [ + "state" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupDmWrap_state` ON `${TABLE_NAME}` (`state`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupEcdhPartial", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`roundId` TEXT NOT NULL, `participantId` INTEGER NOT NULL, `senderPublicKey` TEXT NOT NULL, `partial` TEXT NOT NULL, `proof` TEXT NOT NULL, `verified` INTEGER NOT NULL, `blamedAt` INTEGER, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`roundId`, `participantId`), FOREIGN KEY(`roundId`) REFERENCES `GroupEcdhRound`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "roundId", + "columnName": "roundId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participantId", + "columnName": "participantId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "partial", + "columnName": "partial", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "proof", + "columnName": "proof", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "verified", + "columnName": "verified", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "blamedAt", + "columnName": "blamedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "roundId", + "participantId" + ] + }, + "foreignKeys": [ + { + "table": "GroupEcdhRound", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "roundId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupEcdhRound", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `point` TEXT NOT NULL, `purpose` TEXT NOT NULL, `ref` TEXT, `evidenceJson` TEXT, `state` TEXT NOT NULL, `partialSentAt` INTEGER, `openedAt` INTEGER NOT NULL, `combinedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "point", + "columnName": "point", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "purpose", + "columnName": "purpose", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ref", + "columnName": "ref", + "affinity": "TEXT" + }, + { + "fieldPath": "evidenceJson", + "columnName": "evidenceJson", + "affinity": "TEXT" + }, + { + "fieldPath": "state", + "columnName": "state", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "partialSentAt", + "columnName": "partialSentAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "openedAt", + "columnName": "openedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "combinedAt", + "columnName": "combinedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GroupEcdhRound_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupEcdhRound_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupEcdhRound_point", + "unique": false, + "columnNames": [ + "point" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupEcdhRound_point` ON `${TABLE_NAME}` (`point`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupInboxMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `rumorId` TEXT NOT NULL, `wrapId` TEXT, `conversationId` TEXT NOT NULL, `participants` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `rumorJson` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `generation` INTEGER NOT NULL, `outgoing` INTEGER NOT NULL, `signingSessionId` TEXT, `readAt` INTEGER, `receivedAt` INTEGER NOT NULL, `expiresAt` INTEGER, PRIMARY KEY(`chatRoomId`, `rumorId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "rumorId", + "columnName": "rumorId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "wrapId", + "columnName": "wrapId", + "affinity": "TEXT" + }, + { + "fieldPath": "conversationId", + "columnName": "conversationId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participants", + "columnName": "participants", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "rumorJson", + "columnName": "rumorJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "outgoing", + "columnName": "outgoing", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "signingSessionId", + "columnName": "signingSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "readAt", + "columnName": "readAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "expiresAt", + "columnName": "expiresAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId", + "rumorId" + ] + }, + "indices": [ + { + "name": "index_GroupInboxMessage_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxMessage_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupInboxMessage_conversationId", + "unique": false, + "columnNames": [ + "conversationId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxMessage_conversationId` ON `${TABLE_NAME}` (`conversationId`)" + }, + { + "name": "index_GroupInboxMessage_expiresAt", + "unique": false, + "columnNames": [ + "expiresAt" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxMessage_expiresAt` ON `${TABLE_NAME}` (`expiresAt`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupInboxPublication", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`eventId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `kind` INTEGER NOT NULL, `eventJson` TEXT NOT NULL, `relays` TEXT NOT NULL, `signingSessionId` TEXT, `recipientPublicKey` TEXT, `attempts` INTEGER NOT NULL, `nextAttemptAt` INTEGER, `publishedAt` INTEGER, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`eventId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "eventId", + "columnName": "eventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "eventJson", + "columnName": "eventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relays", + "columnName": "relays", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signingSessionId", + "columnName": "signingSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "recipientPublicKey", + "columnName": "recipientPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "attempts", + "columnName": "attempts", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nextAttemptAt", + "columnName": "nextAttemptAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "publishedAt", + "columnName": "publishedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "eventId" + ] + }, + "indices": [ + { + "name": "index_GroupInboxPublication_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxPublication_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupInboxPublication_signingSessionId", + "unique": false, + "columnNames": [ + "signingSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxPublication_signingSessionId` ON `${TABLE_NAME}` (`signingSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupInboxWrap", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `wrapJson` TEXT NOT NULL, `wrapCreatedAt` INTEGER NOT NULL, `openedGeneration` INTEGER, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "wrapJson", + "columnName": "wrapJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "wrapCreatedAt", + "columnName": "wrapCreatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "openedGeneration", + "columnName": "openedGeneration", + "affinity": "INTEGER" + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GroupInboxWrap_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxWrap_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupKeyState", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `thresholdPublicKey` TEXT NOT NULL, `derivationPath` TEXT NOT NULL, `announcedBy` TEXT NOT NULL, `announcedAt` INTEGER NOT NULL, `parentChatRoomId` TEXT, `birthCertificateJson` TEXT, `generation` INTEGER, `publicSharesHash` TEXT, `memberBindings` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`chatRoomId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "thresholdPublicKey", + "columnName": "thresholdPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "announcedBy", + "columnName": "announcedBy", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "announcedAt", + "columnName": "announcedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "parentChatRoomId", + "columnName": "parentChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "birthCertificateJson", + "columnName": "birthCertificateJson", + "affinity": "TEXT" + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER" + }, + { + "fieldPath": "publicSharesHash", + "columnName": "publicSharesHash", + "affinity": "TEXT" + }, + { + "fieldPath": "memberBindings", + "columnName": "memberBindings", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId" + ] + }, + "indices": [ + { + "name": "index_GroupKeyState_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupKeyState_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupSignedEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `derivationPath` TEXT, `frostSigningSessionId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT" + }, + { + "fieldPath": "frostSigningSessionId", + "columnName": "frostSigningSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GroupSignedEvent_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupSignedEvent_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupSignedEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupSignedEvent_kind` ON `${TABLE_NAME}` (`kind`)" + }, + { + "name": "index_GroupSignedEvent_frostSigningSessionId", + "unique": false, + "columnNames": [ + "frostSigningSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupSignedEvent_frostSigningSessionId` ON `${TABLE_NAME}` (`frostSigningSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "InboxKey", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `generation` INTEGER NOT NULL, `publicKey` TEXT NOT NULL, `secretKey` TEXT, `recoveryData` TEXT, `ceremonyId` TEXT NOT NULL, `state` TEXT NOT NULL, `announcementEventId` TEXT, `createdAt` INTEGER NOT NULL, `announcedAt` INTEGER, `wipedAt` INTEGER, PRIMARY KEY(`chatRoomId`, `userPublicKey`, `generation`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "secretKey", + "columnName": "secretKey", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryData", + "columnName": "recoveryData", + "affinity": "TEXT" + }, + { + "fieldPath": "ceremonyId", + "columnName": "ceremonyId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "state", + "columnName": "state", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "announcementEventId", + "columnName": "announcementEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "announcedAt", + "columnName": "announcedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "wipedAt", + "columnName": "wipedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId", + "userPublicKey", + "generation" + ] + }, + "indices": [ + { + "name": "index_InboxKey_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_InboxKey_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "InboxKeyCeremony", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `participantPublicKeys` TEXT NOT NULL, `stage` TEXT NOT NULL, `hostPublicKey` TEXT, `round1Random` TEXT, `round2AuxRandom` TEXT, `announceRelays` TEXT, `inboxPublicKey` TEXT, `failureReason` TEXT, `culprit` TEXT, `lastMessageAt` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participantPublicKeys", + "columnName": "participantPublicKeys", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "hostPublicKey", + "columnName": "hostPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "round1Random", + "columnName": "round1Random", + "affinity": "TEXT" + }, + { + "fieldPath": "round2AuxRandom", + "columnName": "round2AuxRandom", + "affinity": "TEXT" + }, + { + "fieldPath": "announceRelays", + "columnName": "announceRelays", + "affinity": "TEXT" + }, + { + "fieldPath": "inboxPublicKey", + "columnName": "inboxPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "culprit", + "columnName": "culprit", + "affinity": "TEXT" + }, + { + "fieldPath": "lastMessageAt", + "columnName": "lastMessageAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_InboxKeyCeremony_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_InboxKeyCeremony_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "InboxKeyCeremonyMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `senderPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `InboxKeyCeremony`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "senderPublicKey", + "kind" + ] + }, + "foreignKeys": [ + { + "table": "InboxKeyCeremony", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "InboxSigning", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `manifest` TEXT, `refusal` TEXT, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "manifest", + "columnName": "manifest", + "affinity": "TEXT" + }, + { + "fieldPath": "refusal", + "columnName": "refusal", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId" + ] + }, + "indices": [ + { + "name": "index_InboxSigning_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_InboxSigning_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "KeyShareGeneration", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`dkgSessionId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `secretShare` TEXT, `publicShares` TEXT NOT NULL, `state` TEXT NOT NULL, `refreshSessionId` TEXT, `recoveryData` TEXT, `activatedAt` INTEGER, `wipedAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`dkgSessionId`, `generation`), FOREIGN KEY(`dkgSessionId`) REFERENCES `DkgSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "secretShare", + "columnName": "secretShare", + "affinity": "TEXT" + }, + { + "fieldPath": "publicShares", + "columnName": "publicShares", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "state", + "columnName": "state", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "refreshSessionId", + "columnName": "refreshSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryData", + "columnName": "recoveryData", + "affinity": "TEXT" + }, + { + "fieldPath": "activatedAt", + "columnName": "activatedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "wipedAt", + "columnName": "wipedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "dkgSessionId", + "generation" + ] + }, + "indices": [ + { + "name": "index_KeyShareGeneration_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_KeyShareGeneration_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "DkgSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "dkgSessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "KeyShareMember", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`dkgSessionId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `participantId` INTEGER NOT NULL, `memberPublicKey` TEXT NOT NULL, `hostPublicKey` TEXT NOT NULL, `standing` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`dkgSessionId`, `generation`, `participantId`), FOREIGN KEY(`dkgSessionId`, `generation`) REFERENCES `KeyShareGeneration`(`dkgSessionId`, `generation`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantId", + "columnName": "participantId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "memberPublicKey", + "columnName": "memberPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "hostPublicKey", + "columnName": "hostPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "standing", + "columnName": "standing", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "dkgSessionId", + "generation", + "participantId" + ] + }, + "indices": [ + { + "name": "index_KeyShareMember_dkgSessionId_generation", + "unique": false, + "columnNames": [ + "dkgSessionId", + "generation" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_KeyShareMember_dkgSessionId_generation` ON `${TABLE_NAME}` (`dkgSessionId`, `generation`)" + } + ], + "foreignKeys": [ + { + "table": "KeyShareGeneration", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "dkgSessionId", + "generation" + ], + "referencedColumns": [ + "dkgSessionId", + "generation" + ] + } + ] + }, + { + "tableName": "ShareRefreshConfirmation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`dkgSessionId` TEXT NOT NULL, `baseGeneration` INTEGER NOT NULL, `refreshSessionId` TEXT NOT NULL, `confirmedAt` INTEGER NOT NULL, PRIMARY KEY(`dkgSessionId`, `baseGeneration`))", + "fields": [ + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "baseGeneration", + "columnName": "baseGeneration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "refreshSessionId", + "columnName": "refreshSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "confirmedAt", + "columnName": "confirmedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "dkgSessionId", + "baseGeneration" + ] + } + }, + { + "tableName": "ShareRefreshMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `participantPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `participantPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `ShareRefreshSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participantPublicKey", + "columnName": "participantPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "participantPublicKey", + "kind" + ] + }, + "foreignKeys": [ + { + "table": "ShareRefreshSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ShareRefreshSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `baseGeneration` INTEGER NOT NULL, `recipientIds` TEXT NOT NULL, `withheld` TEXT, `stage` TEXT NOT NULL, `round1Random` TEXT NOT NULL, `auxRandom` TEXT NOT NULL, `dealApprovedAt` INTEGER, `confirmApprovedAt` INTEGER, `approvalRequestedThrough` TEXT, `coordinatorRound1` TEXT, `certificate` TEXT, `failureReason` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "baseGeneration", + "columnName": "baseGeneration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recipientIds", + "columnName": "recipientIds", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "withheld", + "columnName": "withheld", + "affinity": "TEXT" + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "round1Random", + "columnName": "round1Random", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "auxRandom", + "columnName": "auxRandom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dealApprovedAt", + "columnName": "dealApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "confirmApprovedAt", + "columnName": "confirmApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequestedThrough", + "columnName": "approvalRequestedThrough", + "affinity": "TEXT" + }, + { + "fieldPath": "coordinatorRound1", + "columnName": "coordinatorRound1", + "affinity": "TEXT" + }, + { + "fieldPath": "certificate", + "columnName": "certificate", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ShareRefreshSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ShareRefreshSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_ShareRefreshSession_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ShareRefreshSession_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ShareRepairMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `recipientPublicKey` TEXT NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `senderPublicKey`, `kind`, `recipientPublicKey`), FOREIGN KEY(`sessionId`) REFERENCES `ShareRepairSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recipientPublicKey", + "columnName": "recipientPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "senderPublicKey", + "kind", + "recipientPublicKey" + ] + }, + "foreignKeys": [ + { + "table": "ShareRepairSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ShareRepairSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `targetId` INTEGER NOT NULL, `targetPublicKey` TEXT NOT NULL, `targetHostPublicKey` TEXT NOT NULL, `helperIds` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `stage` TEXT NOT NULL, `sessionRandom` TEXT NOT NULL, `helpApprovedAt` INTEGER, `approvalRequested` INTEGER NOT NULL, `failureReason` TEXT, `nParticipants` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "targetId", + "columnName": "targetId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "targetPublicKey", + "columnName": "targetPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "targetHostPublicKey", + "columnName": "targetHostPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "helperIds", + "columnName": "helperIds", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sessionRandom", + "columnName": "sessionRandom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "helpApprovedAt", + "columnName": "helpApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequested", + "columnName": "approvalRequested", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "nParticipants", + "columnName": "nParticipants", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ShareRepairSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ShareRepairSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_ShareRepairSession_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ShareRepairSession_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GovernanceProposal", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `routingId` TEXT NOT NULL, `epoch` INTEGER NOT NULL, `frostSigningSessionId` TEXT NOT NULL, `commitEventId` TEXT NOT NULL, `commitEventJson` TEXT NOT NULL, `peerKeyPackageEventId` TEXT, `priorStateHex` TEXT NOT NULL, `pendingStateHex` TEXT NOT NULL, `stage` TEXT NOT NULL, `thenRotateWithout` TEXT, `promotionOfferId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "routingId", + "columnName": "routingId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "epoch", + "columnName": "epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "frostSigningSessionId", + "columnName": "frostSigningSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "commitEventId", + "columnName": "commitEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "commitEventJson", + "columnName": "commitEventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "peerKeyPackageEventId", + "columnName": "peerKeyPackageEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "priorStateHex", + "columnName": "priorStateHex", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "pendingStateHex", + "columnName": "pendingStateHex", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "thenRotateWithout", + "columnName": "thenRotateWithout", + "affinity": "TEXT" + }, + { + "fieldPath": "promotionOfferId", + "columnName": "promotionOfferId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GovernanceProposal_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GovernanceProposal_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GovernanceProposal_frostSigningSessionId", + "unique": false, + "columnNames": [ + "frostSigningSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GovernanceProposal_frostSigningSessionId` ON `${TABLE_NAME}` (`frostSigningSessionId`)" + }, + { + "name": "index_GovernanceProposal_commitEventId", + "unique": false, + "columnNames": [ + "commitEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GovernanceProposal_commitEventId` ON `${TABLE_NAME}` (`commitEventId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "InReplyToRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`replyingNostrEventId` TEXT NOT NULL, `inReplyToNostrEventId` TEXT NOT NULL, `inReplyToProfilePublicKey` TEXT, `inReplyToRootNostrEventId` TEXT, `inReplyToRootProfilePublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`replyingNostrEventId`, `inReplyToNostrEventId`), FOREIGN KEY(`inReplyToProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`inReplyToRootProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`replyingNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`inReplyToNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`inReplyToRootNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "replyingNostrEventId", + "columnName": "replyingNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "inReplyToNostrEventId", + "columnName": "inReplyToNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "inReplyToProfilePublicKey", + "columnName": "inReplyToProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootNostrEventId", + "columnName": "inReplyToRootNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootProfilePublicKey", + "columnName": "inReplyToRootProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "replyingNostrEventId", + "inReplyToNostrEventId" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "inReplyToProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "inReplyToRootProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "replyingNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "inReplyToNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "inReplyToRootNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotCommitResult", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `peerKeyPackageEventId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `isOneMemberInitialGroupCreation` INTEGER NOT NULL, `commitBytes` BLOB NOT NULL, `welcomeBytes` BLOB, `groupInfoBytes` BLOB, `framedCommitBytes` BLOB NOT NULL, `preCommitExporterSecret` BLOB NOT NULL, `obligationId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "peerKeyPackageEventId", + "columnName": "peerKeyPackageEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isOneMemberInitialGroupCreation", + "columnName": "isOneMemberInitialGroupCreation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "commitBytes", + "columnName": "commitBytes", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "welcomeBytes", + "columnName": "welcomeBytes", + "affinity": "BLOB" + }, + { + "fieldPath": "groupInfoBytes", + "columnName": "groupInfoBytes", + "affinity": "BLOB" + }, + { + "fieldPath": "framedCommitBytes", + "columnName": "framedCommitBytes", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "preCommitExporterSecret", + "columnName": "preCommitExporterSecret", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "obligationId", + "columnName": "obligationId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + } + }, + { + "tableName": "MarmotGroupEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `signature` TEXT NOT NULL, `encryptedContent` TEXT NOT NULL, `expiresAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`id`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "encryptedContent", + "columnName": "encryptedContent", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "expiresAt", + "columnName": "expiresAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "id" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotInnerEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `quotedEventId` TEXT, `marmotGroupEventId` TEXT, `directMessageRecipientPublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`marmotGroupEventId`) REFERENCES `MarmotGroupEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedEventId", + "columnName": "quotedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "directMessageRecipientPublicKey", + "columnName": "directMessageRecipientPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "MarmotGroupEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "marmotGroupEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotKeyPackage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `tlsEncodedMarmotKeyPackage` BLOB NOT NULL, `profile` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`publicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "tlsEncodedMarmotKeyPackage", + "columnName": "tlsEncodedMarmotKeyPackage", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "profile", + "columnName": "profile", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "publicKey" + ], + "referencedColumns": [ + "publicKey" + ] + } + ] + }, + { + "tableName": "MarmotKeyPackageBundle", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `tlsEncodedMarmotKeyPackage` BLOB NOT NULL, `ncryptsecInitPrivateKey` TEXT NOT NULL, `ncryptsecEncryptionPrivateKey` TEXT NOT NULL, `ncryptsecSignaturePrivateKey` TEXT NOT NULL, `consumed` INTEGER NOT NULL, `rotated` INTEGER NOT NULL, `profile` TEXT, `dTag` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "tlsEncodedMarmotKeyPackage", + "columnName": "tlsEncodedMarmotKeyPackage", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "ncryptsecInitPrivateKey", + "columnName": "ncryptsecInitPrivateKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ncryptsecEncryptionPrivateKey", + "columnName": "ncryptsecEncryptionPrivateKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ncryptsecSignaturePrivateKey", + "columnName": "ncryptsecSignaturePrivateKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "consumed", + "columnName": "consumed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "rotated", + "columnName": "rotated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "profile", + "columnName": "profile", + "affinity": "TEXT" + }, + { + "fieldPath": "dTag", + "columnName": "dTag", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_MarmotKeyPackageBundle_publicKey", + "unique": false, + "columnNames": [ + "publicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_MarmotKeyPackageBundle_publicKey` ON `${TABLE_NAME}` (`publicKey`)" + } + ] + }, + { + "tableName": "MarmotRouting", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`routingId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `activeFromEpoch` INTEGER NOT NULL, `retiredAtEpoch` INTEGER, PRIMARY KEY(`routingId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "routingId", + "columnName": "routingId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "activeFromEpoch", + "columnName": "activeFromEpoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "retiredAtEpoch", + "columnName": "retiredAtEpoch", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "routingId" + ] + }, + "indices": [ + { + "name": "index_MarmotRouting_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_MarmotRouting_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotPublishObligation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`obligationId` TEXT NOT NULL, `bytes` BLOB NOT NULL, PRIMARY KEY(`obligationId`))", + "fields": [ + { + "fieldPath": "obligationId", + "columnName": "obligationId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "bytes", + "columnName": "bytes", + "affinity": "BLOB", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "obligationId" + ] + } + }, + { + "tableName": "MarmotOutboundGate", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`groupId` TEXT NOT NULL, `gate` TEXT NOT NULL, PRIMARY KEY(`groupId`))", + "fields": [ + { + "fieldPath": "groupId", + "columnName": "groupId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "gate", + "columnName": "gate", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "groupId" + ] + } + }, + { + "tableName": "MarmotRetainedEpochSecret", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `epoch` INTEGER NOT NULL, `senderDataSecret` BLOB NOT NULL, `encryptionSecret` BLOB NOT NULL, `leafCount` INTEGER NOT NULL, `exporterSecret` BLOB NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`chatRoomId`, `epoch`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "epoch", + "columnName": "epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "senderDataSecret", + "columnName": "senderDataSecret", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "encryptionSecret", + "columnName": "encryptionSecret", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "leafCount", + "columnName": "leafCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "exporterSecret", + "columnName": "exporterSecret", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId", + "epoch" + ] + }, + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotSenderRatchet", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `epoch` INTEGER NOT NULL, `leafIndex` INTEGER NOT NULL, `applicationGeneration` INTEGER NOT NULL, `record` BLOB NOT NULL, PRIMARY KEY(`chatRoomId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "epoch", + "columnName": "epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "leafIndex", + "columnName": "leafIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "applicationGeneration", + "columnName": "applicationGeneration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "record", + "columnName": "record", + "affinity": "BLOB", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId" + ] + }, + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Mention", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `mentionedPublicKey` TEXT NOT NULL, `mentioningNostrEventId` TEXT, `relayUrl` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, FOREIGN KEY(`mentionedPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`mentioningNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mentionedPublicKey", + "columnName": "mentionedPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "mentioningNostrEventId", + "columnName": "mentioningNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "relayUrl", + "columnName": "relayUrl", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "mentionedPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "mentioningNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "NegentropySynchronizeRequest", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `uuid` TEXT NOT NULL, `purpose` TEXT NOT NULL, `status` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `isRecommendedRelay` INTEGER NOT NULL, `level` INTEGER NOT NULL, `synchronizationFilter` TEXT NOT NULL, `ownerPublicKey` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "uuid", + "columnName": "uuid", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "purpose", + "columnName": "purpose", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isRecommendedRelay", + "columnName": "isRecommendedRelay", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "level", + "columnName": "level", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "synchronizationFilter", + "columnName": "synchronizationFilter", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ownerPublicKey", + "columnName": "ownerPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_NegentropySynchronizeRequest_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NegentropySynchronizeRequest_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_NegentropySynchronizeRequest_status", + "unique": false, + "columnNames": [ + "status" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NegentropySynchronizeRequest_status` ON `${TABLE_NAME}` (`status`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "NegentropySynchronizeResult", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `status` TEXT NOT NULL, `negentropySynchronizeRequestId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`negentropySynchronizeRequestId`) REFERENCES `SynchronizeNostrEventResult`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "negentropySynchronizeRequestId", + "columnName": "negentropySynchronizeRequestId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "SynchronizeNostrEventResult", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "negentropySynchronizeRequestId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "NostrEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `pubKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `sig` TEXT NOT NULL, `relayUrl` TEXT, `quotedNostrEventId` TEXT, `quotedAuthorPublicKey` TEXT, `inReplyToNostrEventId` TEXT, `inReplyToAuthorPublicKey` TEXT, `inReplyToRootNostrEventId` TEXT, `inReplyToRootAuthorPublicKey` TEXT, `repostedNostrEventId` TEXT, `repostedAuthorPublicKey` TEXT, `unsignedNostrEventId` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "pubKey", + "columnName": "pubKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sig", + "columnName": "sig", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayUrl", + "columnName": "relayUrl", + "affinity": "TEXT" + }, + { + "fieldPath": "quotedNostrEventId", + "columnName": "quotedNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "quotedAuthorPublicKey", + "columnName": "quotedAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToNostrEventId", + "columnName": "inReplyToNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToAuthorPublicKey", + "columnName": "inReplyToAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootNostrEventId", + "columnName": "inReplyToRootNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootAuthorPublicKey", + "columnName": "inReplyToRootAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "repostedNostrEventId", + "columnName": "repostedNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "repostedAuthorPublicKey", + "columnName": "repostedAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_NostrEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_kind` ON `${TABLE_NAME}` (`kind`)" + }, + { + "name": "index_NostrEvent_pubKey", + "unique": false, + "columnNames": [ + "pubKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_pubKey` ON `${TABLE_NAME}` (`pubKey`)" + }, + { + "name": "index_NostrEvent_quotedNostrEventId", + "unique": false, + "columnNames": [ + "quotedNostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_quotedNostrEventId` ON `${TABLE_NAME}` (`quotedNostrEventId`)" + }, + { + "name": "index_NostrEvent_inReplyToNostrEventId", + "unique": false, + "columnNames": [ + "inReplyToNostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_inReplyToNostrEventId` ON `${TABLE_NAME}` (`inReplyToNostrEventId`)" + }, + { + "name": "index_NostrEvent_inReplyToRootNostrEventId", + "unique": false, + "columnNames": [ + "inReplyToRootNostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_inReplyToRootNostrEventId` ON `${TABLE_NAME}` (`inReplyToRootNostrEventId`)" + } + ] + }, + { + "tableName": "NostrEventRelay", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`relayURL` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`nostrEventId`, `relayURL`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "nostrEventId", + "relayURL" + ] + }, + "indices": [ + { + "name": "index_NostrEventRelay_relayURL", + "unique": false, + "columnNames": [ + "relayURL" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEventRelay_relayURL` ON `${TABLE_NAME}` (`relayURL`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "NotificationLedger", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`userPublicKey` TEXT NOT NULL, `armedAt` INTEGER NOT NULL, `cursorMessageId` INTEGER NOT NULL, `lastBackgroundSyncAt` INTEGER, `lastBackgroundSyncOutcome` TEXT, `lastBackgroundSyncKind` TEXT, `enabled` INTEGER NOT NULL DEFAULT 1, `messages` INTEGER NOT NULL DEFAULT 1, `needsYou` INTEGER NOT NULL DEFAULT 1, `groupActivity` INTEGER NOT NULL DEFAULT 0, `showMessageText` INTEGER NOT NULL DEFAULT 1, PRIMARY KEY(`userPublicKey`))", + "fields": [ + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "armedAt", + "columnName": "armedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "cursorMessageId", + "columnName": "cursorMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastBackgroundSyncAt", + "columnName": "lastBackgroundSyncAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "lastBackgroundSyncOutcome", + "columnName": "lastBackgroundSyncOutcome", + "affinity": "TEXT" + }, + { + "fieldPath": "lastBackgroundSyncKind", + "columnName": "lastBackgroundSyncKind", + "affinity": "TEXT" + }, + { + "fieldPath": "enabled", + "columnName": "enabled", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "1" + }, + { + "fieldPath": "messages", + "columnName": "messages", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "1" + }, + { + "fieldPath": "needsYou", + "columnName": "needsYou", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "1" + }, + { + "fieldPath": "groupActivity", + "columnName": "groupActivity", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "showMessageText", + "columnName": "showMessageText", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "1" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "userPublicKey" + ] + } + }, + { + "tableName": "Participant", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `participantPublicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `adminAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, FOREIGN KEY(`participantPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantPublicKey", + "columnName": "participantPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayHint", + "columnName": "relayHint", + "affinity": "TEXT" + }, + { + "fieldPath": "adminAt", + "columnName": "adminAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "participantPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Post", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `repostId` TEXT, `quote` TEXT, `content` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `replyToId` TEXT, `profilePublicKey` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`profilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`replyToId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "repostId", + "columnName": "repostId", + "affinity": "TEXT" + }, + { + "fieldPath": "quote", + "columnName": "quote", + "affinity": "TEXT" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "replyToId", + "columnName": "replyToId", + "affinity": "TEXT" + }, + { + "fieldPath": "profilePublicKey", + "columnName": "profilePublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Post_profilePublicKey", + "unique": false, + "columnNames": [ + "profilePublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_profilePublicKey` ON `${TABLE_NAME}` (`profilePublicKey`)" + }, + { + "name": "index_Post_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_Post_replyToId", + "unique": false, + "columnNames": [ + "replyToId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_replyToId` ON `${TABLE_NAME}` (`replyToId`)" + }, + { + "name": "index_Post_repostId", + "unique": false, + "columnNames": [ + "repostId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_repostId` ON `${TABLE_NAME}` (`repostId`)" + } + ], + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "profilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "replyToId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Profile", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`publicKey` TEXT NOT NULL, `userName` TEXT, `displayName` TEXT, `picture` TEXT, `banner` TEXT, `website` TEXT, `about` TEXT, `bot` INTEGER, `pronouns` TEXT, `nip05` TEXT, `domain` TEXT, `lud06` TEXT, `lud16` TEXT, `twitter` TEXT, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`publicKey`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userName", + "columnName": "userName", + "affinity": "TEXT" + }, + { + "fieldPath": "displayName", + "columnName": "displayName", + "affinity": "TEXT" + }, + { + "fieldPath": "picture", + "columnName": "picture", + "affinity": "TEXT" + }, + { + "fieldPath": "banner", + "columnName": "banner", + "affinity": "TEXT" + }, + { + "fieldPath": "website", + "columnName": "website", + "affinity": "TEXT" + }, + { + "fieldPath": "about", + "columnName": "about", + "affinity": "TEXT" + }, + { + "fieldPath": "bot", + "columnName": "bot", + "affinity": "INTEGER" + }, + { + "fieldPath": "pronouns", + "columnName": "pronouns", + "affinity": "TEXT" + }, + { + "fieldPath": "nip05", + "columnName": "nip05", + "affinity": "TEXT" + }, + { + "fieldPath": "domain", + "columnName": "domain", + "affinity": "TEXT" + }, + { + "fieldPath": "lud06", + "columnName": "lud06", + "affinity": "TEXT" + }, + { + "fieldPath": "lud16", + "columnName": "lud16", + "affinity": "TEXT" + }, + { + "fieldPath": "twitter", + "columnName": "twitter", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "publicKey" + ] + }, + "indices": [ + { + "name": "index_Profile_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Profile_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "QuotedRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`quotingNostrEventId` TEXT NOT NULL, `quotedNostrEventId` TEXT NOT NULL, `quotedProfilePublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`quotingNostrEventId`, `quotedNostrEventId`), FOREIGN KEY(`quotedProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`quotingNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`quotedNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "quotingNostrEventId", + "columnName": "quotingNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedNostrEventId", + "columnName": "quotedNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedProfilePublicKey", + "columnName": "quotedProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "quotingNostrEventId", + "quotedNostrEventId" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "quotedProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "quotingNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "quotedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Reaction", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `content` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `replyToId` TEXT NOT NULL, `profilePublicKey` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`profilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`replyToId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "replyToId", + "columnName": "replyToId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "profilePublicKey", + "columnName": "profilePublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Reaction_profilePublicKey", + "unique": false, + "columnNames": [ + "profilePublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_profilePublicKey` ON `${TABLE_NAME}` (`profilePublicKey`)" + }, + { + "name": "index_Reaction_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_Reaction_replyToId", + "unique": false, + "columnNames": [ + "replyToId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_replyToId` ON `${TABLE_NAME}` (`replyToId`)" + } + ], + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "profilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "replyToId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "RecentSearch", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`query` TEXT NOT NULL, `synchronizationFilters` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`query`))", + "fields": [ + { + "fieldPath": "query", + "columnName": "query", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "synchronizationFilters", + "columnName": "synchronizationFilters", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "query" + ] + } + }, + { + "tableName": "Relay", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`publicKey` TEXT NOT NULL, `type` TEXT NOT NULL, `url` TEXT NOT NULL, `read` INTEGER NOT NULL, `write` INTEGER NOT NULL, PRIMARY KEY(`publicKey`, `type`, `url`))", + "fields": [ + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "url", + "columnName": "url", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "read", + "columnName": "read", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "write", + "columnName": "write", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "publicKey", + "type", + "url" + ] + } + }, + { + "tableName": "RepostedRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`repostingNostrEventId` TEXT NOT NULL, `repostedNostrEventId` TEXT NOT NULL, `repostedProfilePublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`repostingNostrEventId`, `repostedNostrEventId`), FOREIGN KEY(`repostedProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostedNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostingNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "repostingNostrEventId", + "columnName": "repostingNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "repostedNostrEventId", + "columnName": "repostedNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "repostedProfilePublicKey", + "columnName": "repostedProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "repostingNostrEventId", + "repostedNostrEventId" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostedProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostingNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "SynchronizeNostrEventRequest", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `purpose` TEXT NOT NULL, `status` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `isRecommendedRelay` INTEGER NOT NULL, `level` INTEGER NOT NULL, `synchronizationFilters` TEXT NOT NULL, `ownerPublicKey` TEXT, `nostrEventId` TEXT, `unsignedNostrEventId` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "purpose", + "columnName": "purpose", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isRecommendedRelay", + "columnName": "isRecommendedRelay", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "level", + "columnName": "level", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "synchronizationFilters", + "columnName": "synchronizationFilters", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ownerPublicKey", + "columnName": "ownerPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_SynchronizeNostrEventRequest_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventRequest_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_SynchronizeNostrEventRequest_status", + "unique": false, + "columnNames": [ + "status" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventRequest_status` ON `${TABLE_NAME}` (`status`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UnsignedNostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "unsignedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "SynchronizeNostrEventResult", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_SynchronizeNostrEventResult_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventResult_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "UnsignedNostrEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `pubKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `privateTags` TEXT, `content` TEXT NOT NULL, `signedAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "pubKey", + "columnName": "pubKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "privateTags", + "columnName": "privateTags", + "affinity": "TEXT" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signedAt", + "columnName": "signedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_UnsignedNostrEvent_pubKey", + "unique": false, + "columnNames": [ + "pubKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_UnsignedNostrEvent_pubKey` ON `${TABLE_NAME}` (`pubKey`)" + }, + { + "name": "index_UnsignedNostrEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_UnsignedNostrEvent_kind` ON `${TABLE_NAME}` (`kind`)" + } + ] + }, + { + "tableName": "Zap", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `postId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `receiverPublicKey` TEXT NOT NULL, `message` TEXT, `invoice` TEXT, `amountInMillisatoshis` INTEGER, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`senderPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`receiverPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`postId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "postId", + "columnName": "postId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receiverPublicKey", + "columnName": "receiverPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "message", + "columnName": "message", + "affinity": "TEXT" + }, + { + "fieldPath": "invoice", + "columnName": "invoice", + "affinity": "TEXT" + }, + { + "fieldPath": "amountInMillisatoshis", + "columnName": "amountInMillisatoshis", + "affinity": "INTEGER" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Zap_senderPublicKey", + "unique": false, + "columnNames": [ + "senderPublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_senderPublicKey` ON `${TABLE_NAME}` (`senderPublicKey`)" + }, + { + "name": "index_Zap_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_Zap_postId", + "unique": false, + "columnNames": [ + "postId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_postId` ON `${TABLE_NAME}` (`postId`)" + } + ], + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "senderPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "receiverPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "postId" + ], + "referencedColumns": [ + "id" + ] + } + ] + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'd4864b1d217e8bd4e7d7168749a03b80')" + ] + } +} \ No newline at end of file diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/android/background/StayConnectedService.kt b/composeApp/src/androidMain/kotlin/mobi/giza/android/background/StayConnectedService.kt index 883b32d6..15ac79f0 100644 --- a/composeApp/src/androidMain/kotlin/mobi/giza/android/background/StayConnectedService.kt +++ b/composeApp/src/androidMain/kotlin/mobi/giza/android/background/StayConnectedService.kt @@ -60,6 +60,7 @@ class StayConnectedService : Service() { runtime.synchronization runtime.notary runtime.notifications + runtime.disappearing if (runtime.activeIdentity.value == null) { DefaultIdentity.load(runtime.phoenixGlobal)?.let { identity -> activatedHere = identity diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index f88c0c73..b5aad359 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -899,4 +899,37 @@ Mark as read Reply Message + + Disappearing messages + How long the messages you send last, in direct messages and in quorum and confederation conversations + How long the messages you send here last + Off + Custom… + Use your default (%1$s) + Default (%1$s) + Messages you send are deleted from your devices and from the recipient's Giza after this time, and relays are asked to delete them too. Other apps, screenshots and relays that ignore the request can keep a copy. + If someone does not open Giza within this time, they may never receive the message. + Signing and key ceremony messages always expire. They are kept for at least a day, or a week for key ceremonies, and are not deleted from this device until the ceremony they belong to has finished. + A group's own room follows the group's setting, not this one. + Disappearing messages set to %1$s + Custom length + Length + Choose between 5 minutes and 365 days + Minutes + Hours + Days + Set + Disappears %1$s + Messages you send here disappear after %1$s + New messages you send here disappear after %1$s. + Change + Got it + 1 minute + %1$d minutes + 1 hour + %1$d hours + 1 day + %1$d days + 1 week + %1$d weeks diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt index c1162e86..20b12bc9 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt @@ -1,5 +1,7 @@ package mobi.giza.compose +import mobi.giza.compose.managers.DisappearingMessageSweeper +import mobi.giza.compose.managers.ProtocolRetention import co.touchlab.kermit.Logger import fr.acinq.phoenix.PhoenixGlobal import kotlin.concurrent.atomics.AtomicReference @@ -172,6 +174,19 @@ class GizaRuntime( } } + /** + * Deletes what has disappeared, whenever something falls due, for as long as the process + * lives, and takes down any notification still showing it. docs/disappearing-messages.md, + * Phase 4. Started on first read, beside [notifications]. + */ + val disappearing: Job by lazy { + ioScope.launch { + DisappearingMessageSweeper.run(auxDatabaseManager.auxDatabase, ProtocolRetention) { swept -> + notificationDispatcher.withdraw(swept.messageIds) + } + } + } + /** * One bounded sync while off screen, run by the platform's scheduler: WorkManager, a * BGTaskScheduler task. docs/notifications-and-background-sync.md, Phase 9. @@ -184,6 +199,7 @@ class GizaRuntime( synchronization notary notifications + disappearing }, syncPending = { publicKey -> nostrRepository.observePendingNegentropySynchronizeRequests(publicKey).map { it != null } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt index b9f8c9b8..63ac7a88 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt @@ -12,6 +12,7 @@ import mobi.giza.compose.database.converters.GizaConverters import mobi.giza.compose.database.dao.BroadcastNostrEventReceiptDao import mobi.giza.compose.database.dao.ConfederationCeremonyDao import mobi.giza.compose.database.dao.ConfederationDao +import mobi.giza.compose.database.dao.DisappearingDao import mobi.giza.compose.database.dao.BroadcastNostrEventRequestDao import mobi.giza.compose.database.dao.ChatMessageBroadcastNostrEventReceiptRelationDao import mobi.giza.compose.database.dao.ChatMessageBroadcastNostrEventRequestRelationDao @@ -73,6 +74,8 @@ import mobi.giza.compose.database.model.ChatMessageBroadcastNostrEventRequestRel import mobi.giza.compose.database.model.ChatMessageNostrEventRelation import mobi.giza.compose.database.model.ChatRoom import mobi.giza.compose.database.model.Confederation +import mobi.giza.compose.database.model.DisappearingSetting +import mobi.giza.compose.database.model.ExpiredGiftWrap import mobi.giza.compose.database.model.GroupConversationKey import mobi.giza.compose.database.model.GroupDmMessage import mobi.giza.compose.database.model.GroupDmOutbound @@ -158,6 +161,8 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) ChatMessageNostrEventRelation::class, ChatRoom::class, Confederation::class, + DisappearingSetting::class, + ExpiredGiftWrap::class, ConfederationCeremony::class, ConfederationMember::class, ConfederationSigningAttempt::class, @@ -227,7 +232,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) UnsignedNostrEvent::class, Zap::class ], - version = 49, + version = 50, autoMigrations = [ // v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can // generate the migration itself — nothing existing changes shape. @@ -523,6 +528,13 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) // statements, never in a release, are dropped; the ceremony loses its coordinator; and a // confederation records whose MLS group it holds as its room. See ConfederationSupergroupMigration. AutoMigration(from = 48, to = 49, spec = ConfederationSupergroupMigration::class), + // v50 adds disappearing messages' storage (docs/disappearing-messages.md, Phase 2): the + // nullable ChatRoom.disappearingMessageSecs and disappearingNoticeShownAt, the nullable + // ChatMessage.expiresAt and GiftWrapPayload.expiresAt with an index each, and the + // DisappearingSetting and ExpiredGiftWrap tables. Nullable columns and new tables only, so + // Room generates it. No data moves: an identity with no DisappearingSetting row reads as + // the one-day default, which is D9's upgrade without a data step. + AutoMigration(from = 49, to = 50), ] ) @ConstructedBy(GizaDatabaseConstructor::class) @@ -551,6 +563,8 @@ abstract class GizaDatabase: RoomDatabase() { abstract fun confederationDao(): ConfederationDao + abstract fun disappearingDao(): DisappearingDao + abstract fun confederationCeremonyDao(): ConfederationCeremonyDao abstract fun dkgSessionDao(): DkgSessionDao diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/DisappearingDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/DisappearingDao.kt new file mode 100644 index 00000000..e802fc93 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/DisappearingDao.kt @@ -0,0 +1,212 @@ +package mobi.giza.compose.database.dao + +import androidx.room3.Dao +import androidx.room3.Insert +import androidx.room3.OnConflictStrategy +import androidx.room3.Query +import androidx.room3.Transaction +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Instant +import kotlinx.coroutines.flow.Flow +import mobi.giza.compose.database.model.DisappearingSetting +import mobi.giza.compose.database.model.ExpiredGiftWrap +import mobi.giza.compose.database.model.GiftWrapPayload + +/** The settings and the tombstones of docs/disappearing-messages.md. */ +@Dao +abstract class DisappearingDao { + + // -- the identity's default (D4) --------------------------------------------------------- + + @Query("SELECT defaultSeconds FROM DisappearingSetting WHERE userPublicKey = :userPublicKey") + abstract suspend fun getDefault(userPublicKey: HexKey): Long? + + @Query("SELECT defaultSeconds FROM DisappearingSetting WHERE userPublicKey = :userPublicKey") + abstract fun observeDefault(userPublicKey: HexKey): Flow + + @Insert(onConflict = OnConflictStrategy.REPLACE) + abstract suspend fun upsertSetting(setting: DisappearingSetting) + + // -- a conversation's override (D4) ------------------------------------------------------ + + @Query("SELECT disappearingMessageSecs FROM ChatRoom WHERE id = :chatRoomId") + abstract suspend fun getRoomOverride(chatRoomId: String): Long? + + @Query("SELECT disappearingMessageSecs FROM ChatRoom WHERE id = :chatRoomId") + abstract fun observeRoomOverride(chatRoomId: String): Flow + + @Query("UPDATE ChatRoom SET disappearingMessageSecs = :seconds WHERE id = :chatRoomId") + abstract suspend fun setRoomOverride(chatRoomId: String, seconds: Long?): Int + + @Query("SELECT userPublicKey FROM ChatRoom WHERE id = :chatRoomId") + abstract suspend fun ownerOf(chatRoomId: String): HexKey? + + // -- the one-time notice (D9) ------------------------------------------------------------ + + @Query("SELECT disappearingNoticeShownAt FROM ChatRoom WHERE id = :chatRoomId") + abstract suspend fun noticeShownAt(chatRoomId: String): Instant? + + @Query("SELECT disappearingNoticeShownAt IS NOT NULL FROM ChatRoom WHERE id = :chatRoomId") + abstract fun observeNoticeShown(chatRoomId: String): Flow + + @Query("UPDATE ChatRoom SET disappearingNoticeShownAt = :at WHERE id = :chatRoomId AND disappearingNoticeShownAt IS NULL") + abstract suspend fun markNoticeShown(chatRoomId: String, at: Instant): Int + + // -- tombstones (D6) --------------------------------------------------------------------- + + @Insert(onConflict = OnConflictStrategy.REPLACE) + abstract suspend fun tombstone(wrap: ExpiredGiftWrap) + + @Query("SELECT EXISTS (SELECT 1 FROM ExpiredGiftWrap WHERE id = :wrapId)") + abstract suspend fun isTombstoned(wrapId: HexKey): Boolean + + @Query("DELETE FROM ExpiredGiftWrap WHERE dropAfter <= :now") + abstract suspend fun pruneTombstones(now: Instant): Int + + // -- the sweep (D6, Phase 4) ------------------------------------------------------------- + // + // The cascade runs NostrEvent -> GiftWrapMessage -> GiftWrapSeal -> GiftWrapPayload -> + // ChatMessage, and GiftWrapPayload -> ChatRoom through `initialGiftWrapPayloadId`. So a wrap is + // only ever deleted together with its payload, never before it, and the room is let go of the + // payload first. + + /** Payloads whose expiry has come. Whether each may go yet is the sweeper's question. */ + @Query("SELECT * FROM GiftWrapPayload WHERE expiresAt IS NOT NULL AND expiresAt <= :now") + abstract suspend fun duePayloads(now: Instant): List + + /** The soonest expiry still on this device, which is when the sweeper next has work. */ + @Query("SELECT MIN(expiresAt) FROM GiftWrapPayload WHERE expiresAt IS NOT NULL") + abstract fun observeNextPayloadExpiry(): Flow + + @Query("SELECT id FROM ChatMessage WHERE giftWrapPayloadId = :payloadId") + abstract suspend fun linesOf(payloadId: HexKey): List + + @Query("UPDATE ChatRoom SET initialGiftWrapPayloadId = NULL WHERE initialGiftWrapPayloadId = :payloadId") + abstract suspend fun releaseRoomsFrom(payloadId: HexKey): Int + + /** Every wrap this device sealed or opened for [payloadId]: one per recipient when it sent it. */ + @Query("DELETE FROM NostrEvent WHERE id IN (SELECT nostrEventId FROM GiftWrapMessage WHERE giftWrapPayloadId = :payloadId)") + abstract suspend fun deleteWrapsOf(payloadId: HexKey): Int + + /** The wrap around [sealId], for a payload filed before wraps carried their payload's id. */ + @Query( + "DELETE FROM NostrEvent WHERE id IN (SELECT GiftWrapMessage.nostrEventId FROM GiftWrapMessage " + + "JOIN GiftWrapSeal ON GiftWrapSeal.giftWrapMessageId = GiftWrapMessage.id WHERE GiftWrapSeal.id = :sealId)" + ) + abstract suspend fun deleteWrapOfSeal(sealId: HexKey): Int + + @Query("DELETE FROM GiftWrapPayload WHERE id = :payloadId") + abstract suspend fun deletePayload(payloadId: HexKey): Int + + /** + * Wraps with no payload here -- addressed to somebody else, or never opened -- whose own expiry + * has come. Nothing hangs off them: a wrap that was opened carries its payload's id. + */ + @Query( + "DELETE FROM NostrEvent WHERE id IN (SELECT nostrEventId FROM GiftWrapMessage " + + "WHERE giftWrapPayloadId IS NULL AND expiresAt IS NOT NULL AND expiresAt <= :now)" + ) + abstract suspend fun deleteDueUnlinkedWraps(now: Instant): Int + + /** Ties an opened wrap to what it carried, and to that payload's expiry. */ + @Query("UPDATE GiftWrapMessage SET giftWrapPayloadId = :payloadId, expiresAt = :expiresAt WHERE id = :wrapId") + abstract suspend fun linkWrap(wrapId: HexKey, payloadId: HexKey, expiresAt: Instant?): Int + + @Query("DELETE FROM GiftWrapSeal WHERE giftWrapMessageId = :wrapId") + abstract suspend fun deleteSealsOf(wrapId: HexKey): Int + + @Query("UPDATE NostrEvent SET content = '' WHERE id = :wrapId") + abstract suspend fun blankEvent(wrapId: HexKey): Int + + @Query("UPDATE GiftWrapMessage SET content = '', giftWrapPayloadId = NULL, expiresAt = :dropAfter WHERE id = :wrapId") + abstract suspend fun blankWrap(wrapId: HexKey, dropAfter: Instant): Int + + /** + * A wrap whose message arrived already expired: the seal that this device could read goes at + * once, and the wrap stays as an empty row until [dropAfter], when the sweep's unlinked-wrap + * rule deletes it. Kept rather than deleted now because the sync that delivered it records the + * event's id next, against a foreign key; and while the row is there a re-sync finds it already + * stored and opens nothing. The tombstone covers a relay that serves it after that. + */ + @Transaction + open suspend fun dropOnArrival(wrapId: HexKey, dropAfter: Instant, tombstoneUntil: Instant) { + deleteSealsOf(wrapId) + blankEvent(wrapId) + blankWrap(wrapId, dropAfter) + tombstone(ExpiredGiftWrap(wrapId, tombstoneUntil)) + } + + // -- a group's conversations (Phase 7) ---------------------------------------------------- + // + // A wrap the group opened is kept as an empty row rather than deleted: it is the ledger that + // stops a re-sync from opening and filing the same message again. + + @Query("SELECT rumorJson FROM GroupDmMessage WHERE signingSessionId = :signingSessionId LIMIT 1") + abstract suspend fun groupDmRumorOf(signingSessionId: String): String? + + @Query( + "UPDATE GroupDmWrap SET wrapJson = '', sealJson = NULL WHERE id IN (SELECT wrapId FROM GroupDmMessage " + + "WHERE expiresAt IS NOT NULL AND expiresAt <= :now AND wrapId IS NOT NULL)" + ) + abstract suspend fun blankExpiredGroupDmWraps(now: Instant): Int + + @Query( + "DELETE FROM GroupDmOutbound WHERE signingSessionId IN (SELECT signingSessionId FROM GroupDmMessage " + + "WHERE expiresAt IS NOT NULL AND expiresAt <= :now AND signingSessionId IS NOT NULL)" + ) + abstract suspend fun deleteExpiredGroupDmOutbound(now: Instant): Int + + @Query("DELETE FROM GroupDmMessage WHERE expiresAt IS NOT NULL AND expiresAt <= :now") + abstract suspend fun deleteExpiredGroupDmMessages(now: Instant): Int + + @Query("UPDATE GroupDmWrap SET wrapJson = '', sealJson = NULL WHERE id = :wrapId") + abstract suspend fun blankGroupDmWrap(wrapId: HexKey): Int + + @Query( + "UPDATE GroupInboxWrap SET wrapJson = '' WHERE id IN (SELECT wrapId FROM GroupInboxMessage " + + "WHERE expiresAt IS NOT NULL AND expiresAt <= :now AND wrapId IS NOT NULL AND kind IN (:kinds))" + ) + abstract suspend fun blankExpiredInboxWraps(now: Instant, kinds: List): Int + + @Query( + "DELETE FROM GroupInboxPublication WHERE signingSessionId IN (SELECT signingSessionId FROM GroupInboxMessage " + + "WHERE expiresAt IS NOT NULL AND expiresAt <= :now AND signingSessionId IS NOT NULL AND kind IN (:kinds))" + ) + abstract suspend fun deleteExpiredInboxPublications(now: Instant, kinds: List): Int + + @Query("DELETE FROM GroupInboxMessage WHERE expiresAt IS NOT NULL AND expiresAt <= :now AND kind IN (:kinds)") + abstract suspend fun deleteExpiredInboxMessages(now: Instant, kinds: List): Int + + @Query("UPDATE GroupInboxWrap SET wrapJson = '' WHERE id = :wrapId") + abstract suspend fun blankInboxWrap(wrapId: HexKey): Int + + /** + * A group's expired messages, in both of its conversation kinds: what the group was sent and + * what it sent, the wraps' words, and anything still owed to a relay. Only the kinds a person + * writes: a confederation's statements are filed elsewhere and are the confederation's record. + */ + @Transaction + open suspend fun sweepGroupMessages(now: Instant): Int { + val kinds = mobi.giza.compose.nostr.DisappearingMessages.WRITTEN_KINDS.toList() + blankExpiredGroupDmWraps(now) + deleteExpiredGroupDmOutbound(now) + val dms = deleteExpiredGroupDmMessages(now) + blankExpiredInboxWraps(now, kinds) + deleteExpiredInboxPublications(now, kinds) + return dms + deleteExpiredInboxMessages(now, kinds) + } + + /** + * Deletes [payload] and everything holding its words: its wraps, their seals, its chat lines. + * Returns the ids of the chat lines that went, so a notification showing one can be withdrawn. + */ + @Transaction + open suspend fun sweepPayload(payload: GiftWrapPayload): List { + val lines = linesOf(payload.id) + releaseRoomsFrom(payload.id) + deleteWrapsOf(payload.id) + payload.giftWrapSealId?.let { deleteWrapOfSeal(it) } + deletePayload(payload.id) + return lines + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt index 5ad72c91..ae895ddf 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt @@ -1,5 +1,6 @@ package mobi.giza.compose.database.dao +import mobi.giza.compose.database.repository.DisappearingSettingsStore import androidx.room3.Dao import androidx.room3.Transaction import co.touchlab.kermit.Logger @@ -1273,11 +1274,17 @@ abstract class MarmotOutboundDao( // the room's address, not its id. nostrGroupId = database.marmotRoutingDao().activeRoutingIdFor(chatRoomId), ) + // A Welcome travels as a NIP-17 wrap, and expires like one: after at least the + // ceremony floor, since the invitee may not open the app for days + // (docs/disappearing-messages.md, D2). Stamped before the id is hashed. + val welcomeTags = DisappearingSettingsStore(database).stamp( + chatRoomId, userPublicKey, welcomeEvent.kind, welcomeEvent.createdAt, welcomeEvent.tags, + ) // Compute welcomeEventId val welcomeEventId = EventHasher.hashId( pubKey = userPublicKey, kind = welcomeEvent.kind, - tags = welcomeEvent.tags, + tags = welcomeTags, createdAt = welcomeEvent.createdAt, content = welcomeEvent.content ) @@ -1291,7 +1298,7 @@ abstract class MarmotOutboundDao( publicKey = userPublicKey, chatRoomId = chatRoomId, kind = welcomeEvent.kind, - tags = welcomeEvent.tags, + tags = welcomeTags, content = welcomeEvent.content, createdAt = Instant.fromEpochSeconds(welcomeEvent.createdAt) ) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt index 74a0c665..722414c7 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt @@ -1,5 +1,6 @@ package mobi.giza.compose.database.dao +import mobi.giza.compose.managers.DisappearingMessageSweeper import mobi.giza.compose.managers.ConfederationFollowThrough import androidx.room3.Dao import androidx.room3.Transaction @@ -248,6 +249,11 @@ abstract class NostrDao( if (secret != null && GroupDmReceiver.receive(database, nostrEvent.toEvent(), activeKeyPair.pubKey.toHex(), secret)) return } + // A wrap this device already opened, found expired and deleted: the relay may serve it for + // up to two days more, and opening it again would only find it expired again + // (docs/disappearing-messages.md, D6). + if (nostrEvent.kind == GiftWrapEvent.KIND && database.disappearingDao().isTombstoned(nostrEvent.id)) return + val storedNostrEvent = database.nostrEventDao().getNostrEventById(nostrEvent.id) if (storedNostrEvent == null) { @@ -601,9 +607,23 @@ abstract class NostrDao( throw giftWrapImpersonation // Once this is thrown the database transaction fails and nothing gets saved to the DB... } + // NIP-40: a message already past its expiry is ignored -- not filed, + // not notified, not handed to a ceremony. It can arrive because its + // wrap outlives it on the relay by design, and because re-syncs happen + // (docs/disappearing-messages.md, D6). + val rumorExpiry = decryptedGiftWrapPayload.expiresAt + if (rumorExpiry != null && rumorExpiry <= Clock.System.now()) { + DisappearingMessageSweeper.dropOnArrival( + database, nostrEvent.id, nostrEvent.tags, nostrEvent.createdAt.epochSeconds, rumorExpiry, + ) + return@let + } + database.giftWrapPayloadDao().upsert( decryptedGiftWrapPayload ) + // The wrap is deleted with what it carried, and not before (Phase 4). + database.disappearingDao().linkWrap(giftWrapMessage.id, decryptedGiftWrapPayload.id, rumorExpiry) if (decryptedGiftWrapPayload.kind == ChatMessageEvent.KIND) { logger.d("chatMessageEvent: $decryptedGiftWrapPayload") @@ -2061,7 +2081,8 @@ abstract class NostrDao( // The rumor's own timestamp, not the wrap's -- NIP-17 fuzzes the // wrap and the seal by up to two days to frustrate correlation, and // ordering the feed by that would shuffle the conversation. - createdAt = decryptedGiftWrapPayload.createdAt + createdAt = decryptedGiftWrapPayload.createdAt, + expiresAt = decryptedGiftWrapPayload.expiresAt, ) ) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrNip17Dao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrNip17Dao.kt index 297d29dc..36211b87 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrNip17Dao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrNip17Dao.kt @@ -252,7 +252,11 @@ abstract class NostrNip17Dao( publicKey = giftWrapEvent.pubKey, kind = giftWrapEvent.kind, receiverPublicKey = receiverPublicKey.pubKey, - receiverRelayHit = receiverPublicKey.relayHint?.url + receiverRelayHit = receiverPublicKey.relayHint?.url, + // Linked to what it carries, so the sweeper deletes this wrap with its payload and + // never before it; dropped here when the payload is (docs/disappearing-messages.md, D6). + giftWrapPayloadId = giftWrapPayload.id, + expiresAt = giftWrapPayload.expiresAt, ) ) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt index f5d6a774..f1b2ab9d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt @@ -83,7 +83,7 @@ import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent // room, and re-reads all of them each time a message lands anywhere. Without // this that is a scan of every message this device holds, per room, per // arrival -- work that grows with the whole history rather than with the room. - indices = [Index("chatRoomId")], + indices = [Index("chatRoomId"), Index("expiresAt")], ) data class ChatMessage( @PrimaryKey(autoGenerate = true) @@ -112,6 +112,13 @@ data class ChatMessage( */ val directMessageRecipientPublicKey: HexKey? = null, + /** + * When this line disappears, from its rumor's NIP-40 `expiration`, or null for never. The + * sweeper deletes it, and everything holding its words, from then on; a line that arrives + * already past it is never filed. docs/disappearing-messages.md, D6. + */ + val expiresAt: Instant? = null, + /** * The signing session a [FROST_TYPES] line belongs to, or null for anything else. * diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatRoom.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatRoom.kt index 6dde596d..ab89f4e2 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatRoom.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatRoom.kt @@ -155,6 +155,17 @@ data class ChatRoom( @ColumnInfo(defaultValue = NOTIFICATIONS_ALL) val notifications: String = NOTIFICATIONS_ALL, + /** + * How long what the user writes here lasts, in seconds: null follows the identity's default, + * `0` is Off for this conversation only. Read once per message, when it is queued, and only in + * a NIP-17 room -- an MLS room follows the group's own retention. Local: NIP-17 has no shared + * timer, so each sender's choice rides their own messages. docs/disappearing-messages.md, D4. + */ + val disappearingMessageSecs: Long? = null, + + /** When the one-time "messages now disappear" notice was shown here, or null for not yet (D9). */ + val disappearingNoticeShownAt: Instant? = null, + override val createdAt: Instant = Clock.System.now(), override val updatedAt: Instant = createdAt, override val savedAt: Instant = createdAt, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/DisappearingSetting.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/DisappearingSetting.kt new file mode 100644 index 00000000..74f5112f --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/DisappearingSetting.kt @@ -0,0 +1,32 @@ +package mobi.giza.compose.database.model + +import androidx.room3.Entity +import androidx.room3.PrimaryKey +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Instant + +/** + * An identity's default for how long what it writes in NIP-17 conversations lasts, in seconds; + * `0` is Off. No row reads as [mobi.giza.compose.nostr.DisappearingMessages.DEFAULT_SECONDS], which + * is how a new identity and an upgraded one both start at a day without a data migration. + * docs/disappearing-messages.md, D4 and D9. + */ +@Entity +data class DisappearingSetting( + @PrimaryKey + val userPublicKey: HexKey, + val defaultSeconds: Long, + val updatedAt: Instant, +) + +/** + * A gift wrap this device has already handled and deleted, kept until the wrap's own expiry so a + * re-sync that brings it back is dropped before it is decrypted again. The wrap outlives its rumor + * by up to two days on a relay, by design. docs/disappearing-messages.md, D6. + */ +@Entity +data class ExpiredGiftWrap( + @PrimaryKey + val id: HexKey, + val dropAfter: Instant, +) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GiftWrapMessage.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GiftWrapMessage.kt index 39f0fb50..884fde81 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GiftWrapMessage.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GiftWrapMessage.kt @@ -3,6 +3,7 @@ package mobi.giza.compose.database.model import androidx.room3.Entity import androidx.room3.ForeignKey import androidx.room3.Ignore +import androidx.room3.Index import androidx.room3.PrimaryKey import co.touchlab.kermit.Logger import com.vitorpamplona.quartz.nip01Core.core.HexKey @@ -25,6 +26,7 @@ import kotlin.time.Instant onDelete = ForeignKey.CASCADE, ), ], + indices = [Index("giftWrapPayloadId"), Index("expiresAt")], ) data class GiftWrapMessage( @PrimaryKey @@ -72,6 +74,22 @@ data class GiftWrapMessage( override val savedAt: Instant = Clock.System.now(), override val viewedAt: Instant? = null, override val deletedAt: Instant? = null, // Who this message should be seen by (used to derive conversationId) + + /** + * The payload this wrap carried, when this device knows it: every wrap it sealed, and every + * wrap it opened. Not a foreign key, on purpose -- the cascade already runs the other way, + * wrap to seal to payload -- but it is how the sweeper finds all of a payload's wraps, the + * sender's one-per-recipient copies included, and deletes them with it rather than before it. + * docs/disappearing-messages.md, Phase 4. + */ + val giftWrapPayloadId: HexKey? = null, + + /** + * When this device drops the wrap: its payload's expiry when that is known, else the wrap's + * own NIP-40 `expiration` -- a wrap addressed to somebody else is kept, unopened, and goes + * when the relay would have dropped it. Null for never. docs/disappearing-messages.md, D6. + */ + val expiresAt: Instant? = null, ): mobi.giza.compose.database.model.traits.NostrEventEntity, mobi.giza.compose.database.model.traits.TimestampedEntity, mobi.giza.compose.database.model.traits.LocalStoreEntity, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GiftWrapPayload.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GiftWrapPayload.kt index 77c6750a..1368a680 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GiftWrapPayload.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GiftWrapPayload.kt @@ -3,6 +3,7 @@ package mobi.giza.compose.database.model import androidx.room3.Entity import androidx.room3.ForeignKey import androidx.room3.Ignore +import androidx.room3.Index import androidx.room3.PrimaryKey import mobi.giza.compose.database.model.traits.LocalStoreEntity import mobi.giza.compose.database.model.traits.SoftDeletableEntity @@ -17,6 +18,7 @@ import com.vitorpamplona.quartz.nip01Core.tags.people.taggedUsers import com.vitorpamplona.quartz.nip14Subject.subject import kotlin.time.Clock import kotlin.time.Instant +import mobi.giza.compose.nostr.DisappearingMessages @Entity( foreignKeys = [ @@ -27,6 +29,7 @@ import kotlin.time.Instant onDelete = ForeignKey.CASCADE, ) ], + indices = [Index("expiresAt")], ) data class GiftWrapPayload( @PrimaryKey @@ -78,6 +81,14 @@ data class GiftWrapPayload( override val savedAt: Instant = Clock.System.now(), override val viewedAt: Instant? = null, override val deletedAt: Instant? = null, // Who this message should be seen by (used to derive conversationId) + + /** + * The rumor's NIP-40 `expiration`, or null for never. Read off [tags] by default, so every + * producer -- and the inbound path, which builds this from an unsealed rumor -- records it + * without saying so, and the sweeper finds what is due without parsing every row's tags. + * docs/disappearing-messages.md, D2 and D6. + */ + val expiresAt: Instant? = DisappearingMessages.expirationOf(tags, createdAt.epochSeconds)?.let { Instant.fromEpochSeconds(it) }, ): TimestampedEntity, LocalStoreEntity, UserViewableEntity, SoftDeletableEntity { @Ignore private val logger = Logger.withTag(TAG) @@ -132,6 +143,7 @@ data class GiftWrapPayload( if (content != other.content) return false if (quotedEventId != other.quotedEventId) return false if (giftWrapSealId != other.giftWrapSealId) return false + if (expiresAt != other.expiresAt) return false if (createdAt != other.createdAt) return false if (updatedAt != other.updatedAt) return false if (savedAt != other.savedAt) return false @@ -149,6 +161,7 @@ data class GiftWrapPayload( result = 31 * result + content.hashCode() result = 31 * result + (quotedEventId?.hashCode() ?: 0) result = 31 * result + (giftWrapSealId?.hashCode() ?: 0) + result = 31 * result + (expiresAt?.hashCode() ?: 0) result = 31 * result + createdAt.hashCode() result = 31 * result + updatedAt.hashCode() result = 31 * result + savedAt.hashCode() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupDm.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupDm.kt index 71e31e9c..c379ffb8 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupDm.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupDm.kt @@ -1,5 +1,6 @@ package mobi.giza.compose.database.model +import mobi.giza.compose.nostr.DisappearingMessages import androidx.room3.Entity import androidx.room3.ForeignKey import androidx.room3.Index @@ -128,7 +129,7 @@ data class GroupDmWrap( foreignKeys = [ ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE) ], - indices = [Index("chatRoomId"), Index("conversationId")], + indices = [Index("chatRoomId"), Index("conversationId"), Index("expiresAt")], ) data class GroupDmMessage( @PrimaryKey @@ -145,6 +146,8 @@ data class GroupDmMessage( val signingSessionId: String? = null, val readAt: Instant? = null, val filedAt: Instant = Clock.System.now(), + /** The rumor's NIP-40 expiry, read off [rumorJson]; the sweeper deletes the message from then on. */ + val expiresAt: Instant? = DisappearingMessages.expirationOfRumorJson(rumorJson)?.let { Instant.fromEpochSeconds(it) }, ) /** One recipient's copy of a message the group signed, owed until a relay takes it (D10). */ diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupInbox.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupInbox.kt index 286d0e0f..b73edf04 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupInbox.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupInbox.kt @@ -1,5 +1,6 @@ package mobi.giza.compose.database.model +import mobi.giza.compose.nostr.DisappearingMessages import androidx.room3.Entity import androidx.room3.ForeignKey import androidx.room3.Index @@ -49,7 +50,7 @@ data class GroupInboxWrap( foreignKeys = [ ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE) ], - indices = [Index("chatRoomId"), Index("conversationId")], + indices = [Index("chatRoomId"), Index("conversationId"), Index("expiresAt")], ) data class GroupInboxMessage( val chatRoomId: String, @@ -75,6 +76,8 @@ data class GroupInboxMessage( val signingSessionId: String? = null, val readAt: Instant? = null, val receivedAt: Instant = Clock.System.now(), + /** The rumor's NIP-40 expiry, read off [rumorJson]; the sweeper deletes a reply from then on. */ + val expiresAt: Instant? = DisappearingMessages.expirationOfRumorJson(rumorJson)?.let { Instant.fromEpochSeconds(it) }, ) { fun participantList(): List = participants.split(",").map { it.trim() }.filter { it.isNotEmpty() } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/NostrEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/NostrEvent.kt index 7d2853ac..1800a44d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/NostrEvent.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/NostrEvent.kt @@ -209,6 +209,10 @@ data class NostrEvent( receiverRelayHit = receiverPTag.relayHint?.url, signature = giftWrapEvent.sig, nostrEventId = id, + // The wrap's own expiry until it is opened; filing what it carries replaces + // this with the rumor's (docs/disappearing-messages.md, D6). + expiresAt = mobi.giza.compose.nostr.DisappearingMessages.expirationOf(tags, createdAt.epochSeconds) + ?.let { Instant.fromEpochSeconds(it) }, ) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index 7250f26d..64dac56f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -2,6 +2,7 @@ package mobi.giza.compose.database.repository import mobi.giza.compose.repository.GroupMadeHere import mobi.giza.compose.repository.AdminRoom +import mobi.giza.compose.nostr.DisappearingMessages import mobi.giza.compose.nostr.GroupPost import mobi.giza.compose.nostr.GroupNostrProfile import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent @@ -703,25 +704,33 @@ class DatabaseChatRepository( } val createdAt = Clock.System.now().epochSeconds + // The expiry is one of the rumor's tags, so it goes on before the id is hashed: the + // payload id is the id the recipient arrives at. docs/disappearing-messages.md, D4. + val tags = DisappearingSettingsStore(database).stamp( + chatRoomId = localChatRoom.chatRoom.id, + userPublicKey = localChatRoom.chatRoom.userPublicKey, + kind = messageType, + createdAt = createdAt, + tags = receiverTags.toTypedArray(), + ) val giftWrapPayloadId = EventHasher.hashId( pubKey = localChatRoom.chatRoom.userPublicKey, createdAt = createdAt, - tags = receiverTags.toTypedArray(), + tags = tags, content = text, kind = messageType ) - database.giftWrapPayloadDao().upsert( - GiftWrapPayload( - id = giftWrapPayloadId, - kind = messageType, - tags = receiverTags.toTypedArray(), - createdAt = Instant.fromEpochSeconds(createdAt), - content = text, - chatRoomId = localChatRoom.chatRoom.id, - publicKey = localChatRoom.chatRoom.userPublicKey - ) + val payload = GiftWrapPayload( + id = giftWrapPayloadId, + kind = messageType, + tags = tags, + createdAt = Instant.fromEpochSeconds(createdAt), + content = text, + chatRoomId = localChatRoom.chatRoom.id, + publicKey = localChatRoom.chatRoom.userPublicKey ) + database.giftWrapPayloadDao().upsert(payload) database.chatMessageDao().upsert( ChatMessage( @@ -731,7 +740,8 @@ class DatabaseChatRepository( isUserMessage = true, giftWrapPayloadId = giftWrapPayloadId, marmotGroupEventId = null, - marmotInnerEventId = null + marmotInnerEventId = null, + expiresAt = payload.expiresAt, ) ) } @@ -781,6 +791,16 @@ class DatabaseChatRepository( } } + // Sending it late would publish something its own tag says should already be gone: a + // relay is meant to drop it on arrival and a recipient to ignore it. It stays unsealed and + // the sweeper deletes it -- a person's message at once, a ceremony's round once its + // session has finished with it. docs/disappearing-messages.md, Phase 3. + val rumorExpiry = DisappearingMessages.expirationOf(giftWrapPayload.tags, giftWrapPayload.createdAt.epochSeconds) + if (rumorExpiry != null && DisappearingMessages.isExpired(rumorExpiry, Clock.System.now().epochSeconds)) { + logger.w("Not sealing payload ${giftWrapPayload.id}: it expired before it could be sent") + return + } + database.participantDao().findParticipantsByChatRoomId(giftWrapPayload.chatRoomId).forEach { participant -> if (giftWrapPayload.kind == WelcomeEvent.KIND) { logger.i("Only giftWrap welcomeEvent payload (${giftWrapPayload.id}) to the participant who published the related keyPackage") @@ -825,11 +845,14 @@ class DatabaseChatRepository( content = giftWrapPayload.content ) ) - logger.d("GiftWrap Payload Rumor: ${giftWrapPayloadRumor.toJson()}") - - logger.d("Seal to $participant") + // The rumor is the plaintext of somebody's words, so it is not logged: a log line would + // outlive the message (docs/disappearing-messages.md, Phase 0, check 7). + logger.d("Seal ${giftWrapPayload.id} to ${participant.participantPublicKey}") val payload = giftWrapPayloadRumor.toJson() + // The seal stays untagged, as NIP-59 says it MUST: Giza's group-seal refusals reject + // a tagged one, and quartz's `mergeWith` would append its tag to every rumor it opens + // (docs/disappearing-messages.md, D5). val sealedRumorEvent = nostrSignerSync.signNormal( createdAt = TimeUtils.randomWithTwoDays(), kind = SealEvent.KIND, @@ -839,14 +862,20 @@ class DatabaseChatRepository( toPublicKey = participant.participantPublicKey ) ) - logger.d("SealEvent: ${sealedRumorEvent.toJson()}") + logger.d("SealEvent: ${sealedRumorEvent.id}") + // The wrap asks relays to drop it, by quartz's formula: its own randomized + // `created_at` plus the rumor's lifetime plus two days, which lands after the rumor's + // expiry and never gives away when the rumor was written (D5). + val wrapCreatedAt = TimeUtils.randomWithTwoDays() + val wrapExpiry = DisappearingMessages.wrapExpiration(rumorExpiry, giftWrapPayload.createdAt.epochSeconds, wrapCreatedAt) val giftWrapEvent = wrapperSigner.signNormal( - createdAt = TimeUtils.randomWithTwoDays(), + createdAt = wrapCreatedAt, kind = GiftWrapEvent.KIND, - tags = arrayOf( - PTag.assemble(participant.participantPublicKey, participant.relayHint?.let { NormalizedRelayUrl(it) }) - ), + tags = listOfNotNull( + PTag.assemble(participant.participantPublicKey, participant.relayHint?.let { NormalizedRelayUrl(it) }), + wrapExpiry?.let { arrayOf(DisappearingMessages.TAG, it.toString()) }, + ).toTypedArray(), content = wrapperSigner.nip44Encrypt( plaintext = sealedRumorEvent.toJson(), toPublicKey = participant.participantPublicKey diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DisappearingSettingsStore.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DisappearingSettingsStore.kt new file mode 100644 index 00000000..27ef3314 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DisappearingSettingsStore.kt @@ -0,0 +1,59 @@ +package mobi.giza.compose.database.repository + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import kotlin.time.Clock +import kotlin.time.Instant +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.map +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.DisappearingSetting +import mobi.giza.compose.nostr.DisappearingMessages + +/** + * How long what a person writes lasts: their default, and a conversation's override. + * docs/disappearing-messages.md, D4. The screens read and write through this; the send path asks + * [policyFor] once per message. + */ +class DisappearingSettingsStore(private val database: GizaDatabase) { + + /** The identity's default, a day until they choose otherwise. */ + suspend fun defaultFor(userPublicKey: HexKey): Long = + database.disappearingDao().getDefault(userPublicKey) ?: DisappearingMessages.DEFAULT_SECONDS + + fun observeDefault(userPublicKey: HexKey): Flow = + database.disappearingDao().observeDefault(userPublicKey).map { it ?: DisappearingMessages.DEFAULT_SECONDS } + + suspend fun saveDefault(userPublicKey: HexKey, seconds: Long) { + require(DisappearingMessages.isValidPolicy(seconds)) { "Not a policy: $seconds seconds" } + database.disappearingDao().upsertSetting(DisappearingSetting(userPublicKey, seconds, Clock.System.now())) + } + + /** The conversation's own setting: null follows the default, `0` is Off here only. */ + fun observeOverride(chatRoomId: String): Flow = database.disappearingDao().observeRoomOverride(chatRoomId) + + suspend fun saveOverride(chatRoomId: String, seconds: Long?) { + require(seconds == null || DisappearingMessages.isValidPolicy(seconds)) { "Not a policy: $seconds seconds" } + database.disappearingDao().setRoomOverride(chatRoomId, seconds) + } + + /** Whether the one-time notice has been shown in [chatRoomId] (D9); a room not found reads as shown. */ + fun observeNoticeShown(chatRoomId: String): Flow = + database.disappearingDao().observeNoticeShown(chatRoomId).map { it ?: true } + + suspend fun markNoticeShown(chatRoomId: String, at: Instant) { + database.disappearingDao().markNoticeShown(chatRoomId, at) + } + + /** The policy a message queued now in [chatRoomId] by [userPublicKey] is stamped with. */ + suspend fun policyFor(chatRoomId: String, userPublicKey: HexKey): Long = + DisappearingMessages.policyFor(database.disappearingDao().getRoomOverride(chatRoomId), defaultFor(userPublicKey)) + + /** + * [tags] with the rumor's expiry under the room's policy: what every producer of a NIP-17 + * `GiftWrapPayload` calls *before* it hashes the rumor's id, since the tag is one of the fields + * the id covers. docs/disappearing-messages.md, Phase 3. + */ + suspend fun stamp(chatRoomId: String, userPublicKey: HexKey, kind: Kind, createdAt: Long, tags: Array>): Array> = + DisappearingMessages.stamp(kind, createdAt, policyFor(chatRoomId, userPublicKey), tags) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ChillDkgRitualManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ChillDkgRitualManager.kt index 26646b15..9b7cd9b1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ChillDkgRitualManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ChillDkgRitualManager.kt @@ -1,5 +1,6 @@ package mobi.giza.compose.managers +import mobi.giza.compose.database.repository.DisappearingSettingsStore import mobi.giza.compose.database.model.isGuardedSubgroup import co.touchlab.kermit.Logger @@ -1573,7 +1574,7 @@ object ChillDkgRitualManager { ) } - val tags = receiverTags.toTypedArray() + DkgRitualEvents.assembleTags( + val baseTags = receiverTags.toTypedArray() + DkgRitualEvents.assembleTags( sessionId = session.id, threshold = if (includeThreshold) session.threshold else null, parentChatRoomId = if (includeParent) session.parentChatRoomId else null, @@ -1582,6 +1583,15 @@ object ChillDkgRitualManager { val createdAt = Clock.System.now().epochSeconds + // A NIP-17 round expires like everything else in a wrap, after at least the ceremony + // floor (docs/disappearing-messages.md, D2). The tag is part of the rumor, so it goes on + // before the id is hashed. A Marmot room's rounds follow the group's own retention. + val tags = if (localChatRoom.chatRoom.mlsGroupState == null) { + DisappearingSettingsStore(database).stamp(localChatRoom.chatRoom.id, session.userPublicKey, kind, createdAt, baseTags) + } else { + baseTags + } + // The rumor id the outbound pipeline will recompute from these same // fields when it assembles the event to encrypt, on either transport. val id = EventHasher.hashId( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt index d1cacd5c..2ca324ae 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt @@ -1,5 +1,6 @@ package mobi.giza.compose.managers +import mobi.giza.compose.database.repository.DisappearingSettingsStore import co.touchlab.kermit.Logger import com.vitorpamplona.crypto.random.RandomInstance import com.vitorpamplona.quartz.nip01Core.core.Event @@ -601,12 +602,15 @@ object ConfederationRitualManager { ) { val people = plan?.people ?: (localChatRoom.localParticipants.map { it.participant.participantPublicKey } + localChatRoom.chatRoom.userPublicKey) - val tags = people.filter { it != ceremony.userPublicKey }.sorted().map { arrayOf("p", it) }.toTypedArray() + arrayOf( + val baseTags = people.filter { it != ceremony.userPublicKey }.sorted().map { arrayOf("p", it) }.toTypedArray() + arrayOf( ConfederationRitualEvents.sessionTag(ceremony.id), arrayOf(ConfederationRitualEvents.PROPOSAL_TAG, ceremony.proposalId), arrayOf(ConfederationRitualEvents.ATTEMPT_TAG, ceremony.attempt.toString()), ) val createdAt = Clock.System.now().epochSeconds + // Expires after at least the ceremony floor, stamped before the id is hashed + // (docs/disappearing-messages.md, D2). + val tags = DisappearingSettingsStore(database).stamp(localChatRoom.chatRoom.id, ceremony.userPublicKey, kind, createdAt, baseTags) val id = EventHasher.hashId(pubKey = ceremony.userPublicKey, createdAt = createdAt, kind = kind, tags = tags, content = content) database.giftWrapPayloadDao().upsert( GiftWrapPayload( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/DisappearingMessageSweeper.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/DisappearingMessageSweeper.kt new file mode 100644 index 00000000..208984d9 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/DisappearingMessageSweeper.kt @@ -0,0 +1,117 @@ +package mobi.giza.compose.managers + +import co.touchlab.kermit.Logger +import kotlin.time.Clock +import kotlin.time.Duration +import kotlin.time.Duration.Companion.hours +import kotlin.time.Duration.Companion.seconds +import kotlin.time.Instant +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.collectLatest +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.GiftWrapPayload +import mobi.giza.compose.nostr.DisappearingMessages + +/** + * Whether an expired payload may be deleted yet. What a person wrote may go the moment it expires; + * a ceremony's round has to wait until its session has finished with it, because the session is + * rebuilt from those rows. docs/disappearing-messages.md, D6 and Phase 5. + */ +fun interface PayloadRetention { + suspend fun isReleased(database: GizaDatabase, payload: GiftWrapPayload): Boolean +} + +/** + * Deletes, from this device, what has disappeared: expired NIP-17 payloads with their wraps, seals + * and chat lines; wraps addressed to somebody else once the relay would have dropped them; and + * tombstones that have outlived their wraps. docs/disappearing-messages.md, D6 and Phase 4. + */ +object DisappearingMessageSweeper { + private val logger = Logger.withTag("DisappearingMessageSweeper") + + /** How often the sweeper looks again when nothing is due sooner: a released ceremony, an unopened wrap. */ + val PERIOD: Duration = 1.hours + + data class Swept( + val payloads: Int = 0, + val wraps: Int = 0, + val tombstones: Int = 0, + /** The chat lines that went, so a notification showing one can be withdrawn. */ + val messageIds: Set = emptySet(), + /** Messages this device wrote that expired before they could be sent. */ + val unsent: Int = 0, + ) { + val isEmpty: Boolean get() = payloads == 0 && wraps == 0 && tombstones == 0 + } + + suspend fun sweep( + database: GizaDatabase, + retention: PayloadRetention, + now: Instant = Clock.System.now(), + ): Swept { + val dao = database.disappearingDao() + var payloads = 0 + var unsent = 0 + val messageIds = mutableSetOf() + dao.duePayloads(now).forEach { payload -> + if (!retention.isReleased(database, payload)) return@forEach + messageIds += dao.sweepPayload(payload) + payloads += 1 + // Never sealed, so never sent: sealGiftWrapPayload refused it as too late. + if (payload.giftWrapSealId == null && DisappearingMessages.classOf(payload.kind) == DisappearingMessages.ExpiryClass.Written) unsent += 1 + } + val groupMessages = dao.sweepGroupMessages(now) + val swept = Swept( + payloads = payloads + groupMessages, + wraps = dao.deleteDueUnlinkedWraps(now), + tombstones = dao.pruneTombstones(now), + messageIds = messageIds, + unsent = unsent, + ) + if (!swept.isEmpty) logger.i { "Swept ${swept.payloads} payload(s), ${swept.wraps} wrap(s), ${swept.tombstones} tombstone(s)" } + return swept + } + + /** + * Sweeps whenever something falls due, and every [PERIOD] besides, until cancelled. The soonest + * expiry is observed, so a message stamped to go in five minutes is not left for an hour; a + * sweep that deletes something changes that table and starts the wait again. + */ + suspend fun run(database: GizaDatabase, retention: PayloadRetention, onSwept: suspend (Swept) -> Unit) { + database.disappearingDao().observeNextPayloadExpiry().collectLatest { next -> + next?.let { due -> + val wait = due - Clock.System.now() + if (wait > Duration.ZERO) delay(wait) + } + while (true) { + runCatching { sweep(database, retention) } + .onSuccess { if (!it.isEmpty) onSwept(it) } + .onFailure { logger.e("Sweep failed", it) } + delay(PERIOD) + } + } + } + + /** + * A wrap that arrived carrying a message already past its expiry: never filed, and remembered so + * a re-sync does not open it again before the relay drops it (D6). The wrap's own expiry is + * when that happens; without one, two days past the message's, which is the most the wrap can + * outlive it by (D5). + */ + suspend fun dropOnArrival(database: GizaDatabase, wrapId: String, wrapTags: Array>, wrapCreatedAt: Long, rumorExpiry: Instant) { + val dropAfter = DisappearingMessages.expirationOf(wrapTags, wrapCreatedAt)?.let { Instant.fromEpochSeconds(it) } + ?: (rumorExpiry + DisappearingMessages.WRAP_SLACK.seconds) + database.disappearingDao().dropOnArrival(wrapId, dropAfter, tombstoneUntil = dropAfter + DisappearingMessages.WRAP_SLACK.seconds) + logger.i { "Wrap $wrapId carried a message that expired at $rumorExpiry; not filed" } + } +} + +/** + * What a person wrote goes the moment it expires; nothing else goes yet. The retention Phase 4 + * ships with, so that the sweeper deletes nothing a ceremony still reads before Phase 5 says when + * each protocol is done with its rounds (docs/disappearing-messages.md, Phase 4). + */ +object WrittenOnlyRetention : PayloadRetention { + override suspend fun isReleased(database: GizaDatabase, payload: GiftWrapPayload): Boolean = + DisappearingMessages.classOf(payload.kind) == DisappearingMessages.ExpiryClass.Written +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt index 24222fac..b5625b9b 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt @@ -1,5 +1,6 @@ package mobi.giza.compose.managers +import mobi.giza.compose.database.repository.DisappearingSettingsStore import co.touchlab.kermit.Logger import com.vitorpamplona.crypto.random.RandomInstance import com.vitorpamplona.quartz.nip01Core.core.Event @@ -3180,11 +3181,21 @@ object FrostSigningManager { // the store is stepped past rather than written over. One second of drift // per collision is nothing a protocol message reads, and no caller // publishes faster than [MAX_ID_SEARCH] identical messages a second. + // + // On the NIP-17 transport the rumor also carries its expiry, after at least the signing + // floor (docs/disappearing-messages.md, D2). It is worked out from `created_at`, so it is + // stamped again each time the search steps the second on. A Marmot room's messages + // follow the group's own retention instead. + val store = DisappearingSettingsStore(database) + suspend fun stamped(at: Long): Array> = + if (isMarmotRoom) tags else store.stamp(localChatRoom.chatRoom.id, session.userPublicKey, kind, at, tags) + var createdAt = Clock.System.now().epochSeconds + var rumorTags = stamped(createdAt) var id = EventHasher.hashId( pubKey = session.userPublicKey, createdAt = createdAt, - tags = tags, + tags = rumorTags, content = content, kind = kind ) @@ -3192,10 +3203,11 @@ object FrostSigningManager { while (attempts < MAX_ID_SEARCH && isQueued(database, isMarmotRoom, id)) { createdAt += 1 + rumorTags = stamped(createdAt) id = EventHasher.hashId( pubKey = session.userPublicKey, createdAt = createdAt, - tags = tags, + tags = rumorTags, content = content, kind = kind ) @@ -3232,7 +3244,7 @@ object FrostSigningManager { publicKey = session.userPublicKey, kind = kind, createdAt = Instant.fromEpochSeconds(createdAt), - tags = tags, + tags = rumorTags, content = content, chatRoomId = localChatRoom.chatRoom.id ) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmReceiver.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmReceiver.kt index ac477406..e39e686d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmReceiver.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmReceiver.kt @@ -1,5 +1,6 @@ package mobi.giza.compose.managers +import mobi.giza.compose.nostr.DisappearingMessages import co.touchlab.kermit.Logger import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey @@ -156,6 +157,10 @@ object GroupDmReceiver { val rumor = GroupDmSeal.open(seal, kept.conversationKey.hexToByteArray()) if (rumor == null) { dao.upsertWrap(ledger.copy(state = GroupDmWrapState.UNREADABLE)) + } else if (DisappearingMessages.expirationOf(rumor.tags, rumor.createdAt)?.let { DisappearingMessages.isExpired(it, Clock.System.now().epochSeconds) } == true) { + // NIP-40: already gone. Not filed, and the ledger keeps the wrap's id but not its + // words, so a re-sync does not open it again (docs/disappearing-messages.md, D6). + dao.upsertWrap(ledger.copy(state = GroupDmWrapState.OPENED, wrapJson = "", sealJson = null)) } else { file(database, context.roomId, rumor, wrapId = ledger.id) dao.upsertWrap(ledger.copy(state = GroupDmWrapState.OPENED)) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmRefusal.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmRefusal.kt index 62dd1af7..1849f200 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmRefusal.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmRefusal.kt @@ -1,5 +1,6 @@ package mobi.giza.compose.managers +import mobi.giza.compose.nostr.DisappearingMessages import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray @@ -134,6 +135,11 @@ object GroupDmRefusal { if (tagged.toSet() != recipients.toSet() || tagged.size != recipients.size) { return Verdict.Declined(REASON, "the message names other recipients than the manifest") } + // Its expiry, when it has one, is a length a person could have chosen: the quorum signs + // how long the message lasts along with what it says (docs/disappearing-messages.md, D10). + if (!DisappearingMessages.isAcceptableExpiry(rumor.tags, rumor.createdAt)) { + return Verdict.Declined(REASON, "the message would disappear sooner or later than any setting allows") + } // 6. Back-dated as NIP-59 does, and not from the future. events.forEach { seal -> diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmSender.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmSender.kt index 0ad71d94..ffc27f92 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmSender.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmSender.kt @@ -1,5 +1,7 @@ package mobi.giza.compose.managers +import mobi.giza.compose.database.repository.DisappearingSettingsStore +import mobi.giza.compose.nostr.DisappearingMessages import co.touchlab.kermit.Logger import com.vitorpamplona.crypto.random.RandomInstance import com.vitorpamplona.quartz.nip01Core.core.Event @@ -108,8 +110,11 @@ object GroupDmSender { if (still.isNotEmpty()) return Outcome.Preparing(still) } - val tags = to.map { arrayOf("p", it) } + listOfNotNull(replyTo?.let { arrayOf("e", it, "", "reply") }) - val rumor = GroupDmSeal.rumor(roomId, now, 14, tags.toTypedArray(), text) + val baseTags = to.map { arrayOf("p", it) } + listOfNotNull(replyTo?.let { arrayOf("e", it, "", "reply") }) + // The expiry is in the rumor, so every signer reads and approves it with the words + // (docs/disappearing-messages.md, D10): the proposer's policy for this room. + val tags = DisappearingSettingsStore(database).stamp(localChatRoom.chatRoom.id, userPublicKey, 14, now, baseTags.toTypedArray()) + val rumor = GroupDmSeal.rumor(roomId, now, 14, tags, text) val seals = to.map { r -> val key = database.groupDmDao().getConversationKey(roomId, r)!!.conversationKey.hexToByteArray() GroupDmSeal.build(rumor, key, createdAt = now - randomBackdate()) @@ -198,10 +203,16 @@ object GroupDmSender { private suspend fun wrapOwed(database: GizaDatabase, signingSessionId: String, signedEvents: List): Int { val dao = database.groupDmDao() var wrapped = 0 + // The rumor's lifetime, which quartz turns into the wrap's own expiry (D5). + val lifetime = database.disappearingDao().groupDmRumorOf(signingSessionId)?.let { json -> + val createdAt = runCatching { com.vitorpamplona.quartz.nip59Giftwrap.rumors.Rumor.fromJson(json).createdAt }.getOrNull() + val expiry = DisappearingMessages.expirationOfRumorJson(json) + if (createdAt != null && expiry != null) expiry - createdAt else null + } dao.getOutbound(signingSessionId).filter { it.wrapJson == null }.forEach { row -> val signed = signedEvents.firstOrNull { it.id == row.sealId }?.takeIf { it.verify() } ?: return@forEach // Ordinary NIP-59: a fresh key of this device's, no group secret involved. - val wrap = GiftWrapEvent.create(event = signed, recipientPubKey = row.recipient) + val wrap = GiftWrapEvent.create(event = signed, recipientPubKey = row.recipient, expirationDelta = lifetime) dao.upsertOutbound(row.copy(wrapJson = wrap.toJson())) wrapped += 1 } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt index 31f3ab65..24dffd7c 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt @@ -1,5 +1,6 @@ package mobi.giza.compose.managers +import mobi.giza.compose.nostr.DisappearingMessages import co.touchlab.kermit.Logger import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey @@ -97,6 +98,13 @@ object GroupInboxManager { database.groupInboxDao().markOpened(wrap.id, key.generation) return null } + // NIP-40: a message already past its expiry is not filed; the ledger keeps the wrap's id + // but not its words (docs/disappearing-messages.md, D6). + if (DisappearingMessages.expirationOf(rumor.tags, rumor.createdAt)?.let { DisappearingMessages.isExpired(it, Clock.System.now().epochSeconds) } == true) { + database.groupInboxDao().markOpened(wrap.id, key.generation) + database.disappearingDao().blankInboxWrap(wrap.id) + return null + } val participants = InboxConversation.participantsOf(rumor, roomId) val message = GroupInboxMessage( chatRoomId = roomId, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRefusal.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRefusal.kt index a85174d8..7e9bfb53 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRefusal.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRefusal.kt @@ -1,5 +1,6 @@ package mobi.giza.compose.managers +import mobi.giza.compose.nostr.DisappearingMessages import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import mobi.giza.compose.database.GizaDatabase @@ -45,6 +46,7 @@ object InboxRefusal { const val REPLY_WRONG_KEY = "Giza doesn't sign a reply sealed to a key its recipient didn't announce" const val REPLY_BLANK = "Giza doesn't sign a reply with nothing in it" const val REPLY_TIME = "Giza doesn't sign a reply dated outside the last two days" + const val REPLY_EXPIRY = "Giza doesn't sign a reply that would disappear sooner or later than any setting allows" private const val TWO_DAYS = 2 * 24 * 60 * 60L private const val CLOCK_SLACK = 10 * 60L @@ -126,6 +128,8 @@ object InboxRefusal { is Read.Ok -> result.reply } if (read.rumor.content.isBlank()) return REPLY_BLANK + // docs/disappearing-messages.md, D10: how long it lasts is signed with what it says. + if (!DisappearingMessages.isAcceptableExpiry(read.rumor.tags, read.rumor.createdAt)) return REPLY_EXPIRY if (events.any { it.createdAt < now - TWO_DAYS - CLOCK_SLACK || it.createdAt > now + CLOCK_SLACK }) return REPLY_TIME return null } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt index 3de1086f..d596aa7b 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt @@ -1,5 +1,7 @@ package mobi.giza.compose.managers +import mobi.giza.compose.database.repository.DisappearingSettingsStore +import mobi.giza.compose.nostr.DisappearingMessages import co.touchlab.kermit.Logger import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey @@ -56,6 +58,8 @@ object InboxReplies { generation: Int, now: Long = TimeUtils.now(), sealTime: () -> Long = { TimeUtils.randomWithTwoDays() }, + /** How long the reply lasts: the proposer's policy, signed with the words (docs/disappearing-messages.md, D10). */ + disappearAfter: Long = DisappearingMessages.OFF, ): Built { require(text.isNotBlank()) { "A reply needs something to say" } require(recipients.isNotEmpty()) { "A reply needs someone to go to" } @@ -64,7 +68,8 @@ object InboxReplies { ordered.forEach { add(arrayOf("p", it.publicKey)) } replyTo?.let { add(arrayOf("e", it, "", "reply")) } }.toTypedArray() - val rumor = RumorAssembler.assembleRumor(pubKey = roomId, ev = EventTemplate(now, 14, tags, text)) + val stamped = DisappearingMessages.stamp(14, now, disappearAfter, tags) + val rumor = RumorAssembler.assembleRumor(pubKey = roomId, ev = EventTemplate(now, 14, stamped, text)) return sealRumor(roomId, rumor, ordered, inboxSecret, generation, sealTime) } @@ -128,6 +133,7 @@ object InboxReplies { replyTo = conversation.lastOrNull { !it.outgoing }?.rumorId, inboxSecret = key.secretKey!!.hexToByteArray(), generation = key.generation, + disappearAfter = DisappearingSettingsStore(database).policyFor(roomId, userPublicKey), ) val sealed = built.manifest.seal(key.secretKey.hexToByteArray()) val session = FrostSigningManager.proposeSigningBatch( @@ -189,14 +195,21 @@ object InboxReplies { val ordered = database.frostSigningSessionDao().getItems(session.id).sortedBy { it.itemIndex }.map { signedById[it.eventId] } if (ordered.size != manifest.seals.size) return + // The rumor's lifetime, read from the group's own copy: each wrap asks relays to drop it a + // random up-to-two-days after the rumor goes, by quartz's formula (docs/disappearing-messages.md, D5). + val selfKey = InboxReplyManifest.selfConversationKey(key.secretKey!!.hexToByteArray()) + val written = ordered[manifest.groupCopy]?.let { InboxSeal.rumorInside(it.content, selfKey, roomId) } + val rumorExpiry = written?.let { DisappearingMessages.expirationOf(it.tags, it.createdAt) } manifest.seals.forEachIndexed { index, entry -> val seal = ordered[index] ?: return@forEachIndexed + val wrapCreatedAt = TimeUtils.randomWithTwoDays() + val wrapExpiry = written?.let { DisappearingMessages.wrapExpiration(rumorExpiry, it.createdAt, wrapCreatedAt) } val relays = if (index == manifest.groupCopy) { InboxAnnouncements.relaysOf(database, roomId) } else { relaysOf(database, entry.recipient) } - val wrap = InboxWrap.wrap(seal, entry.recipient, entry.key, relays.firstOrNull()) + val wrap = InboxWrap.wrap(seal, entry.recipient, entry.key, relays.firstOrNull(), createdAt = wrapCreatedAt, expiration = wrapExpiry) database.groupInboxDao().upsertPublication( GroupInboxPublication( eventId = wrap.id, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ProtocolRetention.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ProtocolRetention.kt new file mode 100644 index 00000000..97e0006f --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ProtocolRetention.kt @@ -0,0 +1,47 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.GiftWrapPayload +import mobi.giza.compose.database.model.types.DkgRitualStage +import mobi.giza.compose.database.model.types.FrostSigningStage +import mobi.giza.compose.nostr.DisappearingMessages +import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents +import mobi.giza.compose.nostr.dkg.DkgRitualEvents +import mobi.giza.compose.nostr.frost.FrostSigningEvents + +/** + * When an expired NIP-17 payload may leave this device. docs/disappearing-messages.md, D6 and + * Phase 5. + * + * Three managers rebuild an open session from the payloads stored for it -- `ChillDkgRitualManager`, + * `FrostSigningManager` and `ConfederationRitualManager` -- so a round is kept, past its expiry, + * until the session it names has completed or failed. What the session produced (the shares, the + * signature, the key) lives on the session's own row and never expires; only the messages that + * carried it do. + * + * A round whose session this device does not have is released: no session here will read it, and + * a round expires only after its floor, a day for signing and a week for a key ceremony, by which + * time a session that was going to be made from it has been. Everything else -- what a person + * wrote, a Welcome, which is processed the moment it arrives, a kind nobody reads back -- is + * released at its expiry. + */ +object ProtocolRetention : PayloadRetention { + override suspend fun isReleased(database: GizaDatabase, payload: GiftWrapPayload): Boolean = when { + DisappearingMessages.classOf(payload.kind) == DisappearingMessages.ExpiryClass.Written -> true + payload.kind == WelcomeEvent.KIND -> true + payload.kind in DkgRitualEvents.ALL -> { + val session = DkgRitualEvents.parseSessionId(payload.tags)?.let { database.dkgSessionDao().getSessionById(it) } + session == null || session.stage == DkgRitualStage.COMPLETE || session.stage == DkgRitualStage.FAILED + } + payload.kind in FrostSigningEvents.ALL -> { + val session = FrostSigningEvents.parseSessionId(payload.tags)?.let { database.frostSigningSessionDao().getSessionById(it) } + session == null || session.stage == FrostSigningStage.COMPLETE || session.stage == FrostSigningStage.FAILED + } + payload.kind in ConfederationRitualEvents.ALL -> { + val ceremony = ConfederationRitualEvents.parseSessionId(payload.tags)?.let { database.confederationCeremonyDao().getCeremony(it) } + ceremony == null || !ceremony.isRunning + } + else -> true + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/DisappearingMessages.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/DisappearingMessages.kt new file mode 100644 index 00000000..2069948b --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/DisappearingMessages.kt @@ -0,0 +1,181 @@ +package mobi.giza.compose.nostr + +import com.vitorpamplona.quartz.nip59Giftwrap.rumors.Rumor +import com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent +import com.vitorpamplona.quartz.nip01Core.core.Kind +import com.vitorpamplona.quartz.nip09Deletions.DeletionRequestEvent +import com.vitorpamplona.quartz.nip17Dm.files.ChatMessageEncryptedFileHeaderEvent +import com.vitorpamplona.quartz.nip17Dm.messages.ChatMessageEvent +import com.vitorpamplona.quartz.nip25Reactions.ReactionEvent +import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents +import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents +import mobi.giza.compose.nostr.dkg.DkgRitualEvents +import mobi.giza.compose.nostr.frost.FrostSigningEvents +import mobi.giza.compose.nostr.frost.ShareRefreshEvents +import mobi.giza.compose.nostr.frost.ShareRepairEvents +import mobi.giza.compose.nostr.groupdm.GroupEcdhEvents +import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents + +/** + * When a NIP-17 rumor expires, worked out once, when it is queued. See + * docs/disappearing-messages.md. + * + * Every event Giza sends in a NIP-17 wrap expires (D2). What a person writes expires after their + * policy, which may be Off. A protocol message always expires, after the longer of the policy and + * the floor its protocol needs, because a ceremony round that outlived its ceremony on a relay + * would be the one exception to "everything expires". + * + * Pure functions of their arguments, with no database, so the rules are testable without Room. + */ +object DisappearingMessages { + /** NIP-40's tag. */ + const val TAG = "expiration" + + /** The policy that means "what I write does not expire". Protocol messages still do. */ + const val OFF: Long = 0L + + const val MINUTE: Long = 60L + const val HOUR: Long = 60 * MINUTE + const val DAY: Long = 24 * HOUR + + /** Below this, two phones' clocks and a slow catch-up can deliver a message already expired (D3). */ + const val MIN_SECONDS: Long = 5 * MINUTE + + /** Long enough that "a long time" is a real choice, short enough that relays treat it sanely (D3). */ + const val MAX_SECONDS: Long = 365 * DAY + + /** The policy a new identity starts with, and an existing one is given on upgrade (D9). */ + const val DEFAULT_SECONDS: Long = DAY + + /** What the settings list offers, Off first. Anything else in bounds is a custom length. */ + val PRESETS: List = listOf(OFF, HOUR, 8 * HOUR, DAY, 7 * DAY, 28 * DAY) + + /** + * A signing round's floor. `docs/frost-session-resend.md` already repairs a round a relay + * dropped, so this only stops a one-hour policy from turning every signing into a race. + */ + const val SIGNING_FLOOR: Long = DAY + + /** A key ceremony's floor: it waits for every admin, and a DKG round has no resend. */ + const val CEREMONY_FLOOR: Long = 7 * DAY + + /** What a kind nobody classified gets: it still expires, never "never" (D2). */ + const val UNCLASSIFIED_FLOOR: Long = CEREMONY_FLOOR + + /** + * How far past the rumor's expiry the wrap's can fall, the same two days quartz adds + * (`GiftWrapEvent.build`), so that the randomized `created_at` never expires a wrap early. + */ + const val WRAP_SLACK: Long = 2 * DAY + + /** The kinds a person writes: their words, a reaction to them, the deletion of one (D2). */ + val WRITTEN_KINDS: Set = setOf( + ChatMessageEvent.KIND, + ChatMessageEncryptedFileHeaderEvent.KIND, + ReactionEvent.KIND, + DeletionRequestEvent.KIND, + ) + + private val SIGNING_KINDS: Set = + FrostSigningEvents.ALL + ConfederationSigningEvents.ALL + GroupEcdhEvents.ALL + + private val CEREMONY_KINDS: Set = + DkgRitualEvents.ALL + InboxKeyRitualEvents.ALL + ShareRefreshEvents.ALL + + ShareRepairEvents.ALL + ConfederationRitualEvents.ALL + setOf(WelcomeEvent.KIND) + + /** Confederation statements carry their own expiry, the proposal's; this is only its ceiling. */ + private val STATEMENT_KINDS: Set = ConfederationKinds.ALL + + sealed interface ExpiryClass { + /** Something a person wrote: it follows their policy, Off included. */ + data object Written : ExpiryClass + + /** + * A protocol message: it always expires, after at least [floorSeconds]. [classified] is + * false for a kind that fell through to [UNCLASSIFIED_FLOOR], which a test refuses for + * every kind the app is known to send. + */ + data class Protocol(val floorSeconds: Long, val classified: Boolean = true) : ExpiryClass + } + + fun classOf(kind: Kind): ExpiryClass = when (kind) { + in WRITTEN_KINDS -> ExpiryClass.Written + in SIGNING_KINDS -> ExpiryClass.Protocol(SIGNING_FLOOR) + in CEREMONY_KINDS -> ExpiryClass.Protocol(CEREMONY_FLOOR) + in STATEMENT_KINDS -> ExpiryClass.Protocol(ConfederationKinds.MAX_EXPIRY_SECONDS) + else -> ExpiryClass.Protocol(UNCLASSIFIED_FLOOR, classified = false) + } + + /** Whether [seconds] is a policy a person may choose: Off, or within the bounds. */ + fun isValidPolicy(seconds: Long): Boolean = seconds == OFF || seconds in MIN_SECONDS..MAX_SECONDS + + /** The policy in force: the conversation's override when it has one, else the identity's default (D4). */ + fun policyFor(roomOverride: Long?, identityDefault: Long): Long = roomOverride ?: identityDefault + + /** + * The rumor's expiry, or null when it has none: a written kind under the policy Off, and + * nothing else. A rumor that already carries a valid expiry keeps it (D5): a second tag would + * get a confederation statement refused. + */ + fun expiryFor(kind: Kind, createdAt: Long, policy: Long, tags: Array>): Long? { + expirationOf(tags, createdAt)?.let { return it } + return when (val expiryClass = classOf(kind)) { + ExpiryClass.Written -> if (policy == OFF) null else createdAt + policy + is ExpiryClass.Protocol -> createdAt + maxOf(policy, expiryClass.floorSeconds) + } + } + + /** + * [tags] with the rumor's expiry added, or unchanged when it already has one or should have + * none. Call it before hashing the rumor's id: the tag is one of the fields the id covers. + */ + fun stamp(kind: Kind, createdAt: Long, policy: Long, tags: Array>): Array> { + if (expirationOf(tags, createdAt) != null) return tags + val expiry = expiryFor(kind, createdAt, policy, tags) ?: return tags + return tags + arrayOf(arrayOf(TAG, expiry.toString())) + } + + /** + * The wrap's expiry: quartz's formula, `wrap.created_at + (rumor's lifetime) + 2 days`. The + * wrap's `created_at` is already up to two days in the past, so this is the rumor's expiry + * plus a random `[0, 2 days]`: later than the sender meant, never earlier, and not an exact + * offset from a time the randomization was there to hide. Null when the rumor has none. + */ + fun wrapExpiration(rumorExpiration: Long?, rumorCreatedAt: Long, wrapCreatedAt: Long): Long? { + val lifetime = (rumorExpiration ?: return null) - rumorCreatedAt + if (lifetime <= 0) return null + return wrapCreatedAt + lifetime + WRAP_SLACK + } + + /** + * The first `expiration` tag's time, or null when there is none or it is malformed: not a + * number, or not after [createdAt]. quartz reads an expiry at or before `created_at` as no + * lifetime at all, and so does this. + */ + fun expirationOf(tags: Array>, createdAt: Long? = null): Long? { + val value = tags.firstOrNull { it.size >= 2 && it[0] == TAG }?.get(1)?.toLongOrNull() ?: return null + if (createdAt != null && value <= createdAt) return null + return value + } + + /** [expirationOf] for a rumor kept as JSON, as a group's conversations keep theirs. */ + fun expirationOfRumorJson(json: String): Long? { + val rumor = runCatching { Rumor.fromJson(json) }.getOrNull() ?: return null + return expirationOf(rumor.tags ?: return null, rumor.createdAt) + } + + /** + * Whether a rumor a signer is asked to sign may carry the expiry it does: none, or a lifetime a + * person could have chosen. A group signs its messages by quorum, so a proposal that would + * vanish in a second or never is refused out loud rather than signed (D10). + */ + fun isAcceptableExpiry(tags: Array>, createdAt: Long): Boolean { + val tag = tags.firstOrNull { it.size >= 2 && it[0] == TAG } ?: return true + val value = tag[1].toLongOrNull() ?: return false + return value - createdAt in MIN_SECONDS..MAX_SECONDS + } + + /** NIP-40: an event is expired from its expiry on. */ + fun isExpired(expiresAt: Long, now: Long): Boolean = now >= expiresAt +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxWrap.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxWrap.kt index 48201982..9ace7861 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxWrap.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxWrap.kt @@ -37,6 +37,8 @@ object InboxWrap { recipientEncryptionKey: HexKey, relayHint: NormalizedRelayUrl? = null, createdAt: Long = TimeUtils.randomWithTwoDays(), + /** The NIP-40 expiry relays are asked to drop it at, or null for none (docs/disappearing-messages.md, D5). */ + expiration: Long? = null, ): Event { val signer = NostrSignerSync(KeyPair()) val throwaway = requireNotNull(signer.keyPair.privKey) @@ -44,7 +46,7 @@ object InboxWrap { return signer.sign( createdAt = createdAt, kind = KIND, - tags = arrayOf(PTag.assemble(recipientIdentity, relayHint)), + tags = listOfNotNull(PTag.assemble(recipientIdentity, relayHint), expiration?.let { arrayOf("expiration", it.toString()) }).toTypedArray(), content = content, ) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationDispatcher.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationDispatcher.kt index 565b1b2e..14251e56 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationDispatcher.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationDispatcher.kt @@ -145,6 +145,20 @@ class NotificationDispatcher( } } + /** + * Takes away every notification showing one of [messageIds]: lines the disappearing-message + * sweeper has deleted. A notification left up would be the message's last copy on the device + * (docs/disappearing-messages.md, D6). + */ + suspend fun withdraw(messageIds: Set) { + if (messageIds.isEmpty()) return + val gone = showingMutex.withLock { + showing.values.filter { notification -> notification.lines.any { it.messageId in messageIds } } + .onEach { showing.remove(it.key) } + } + gone.forEach { notifier.cancel(it.key) } + } + /** Takes a room's notifications away once the room has been read past them. D8. */ private suspend fun cancelWhatWasRead(userPublicKey: HexKey) { database.chatRoomDao().observeChatRoomListByUserPublicKey(userPublicKey).collect { rooms -> diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationPolicy.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationPolicy.kt index c0d3c242..f23ddb62 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationPolicy.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationPolicy.kt @@ -42,6 +42,8 @@ sealed interface NotificationDecision { AlreadyRead, /** Written long ago, however recently it was filed: backfill, not news. */ TooOld, + /** Past its NIP-40 expiry: it has disappeared, and a notification would be its last copy. */ + Expired, } } @@ -73,6 +75,7 @@ object NotificationPolicy { ?: return drop(NotificationDecision.Reason.NotNotifiable) return when { + line.expiresAt != null && line.expiresAt <= now -> drop(NotificationDecision.Reason.Expired) !settings.enabled -> drop(NotificationDecision.Reason.NotificationsOff) !settings.allows(category) -> drop(NotificationDecision.Reason.CategoryOff) room == null || room.deletedAt != null || room.leftGroupAt != null -> diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ActiveProfileScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ActiveProfileScreen.kt index d29036b5..d1caae9a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ActiveProfileScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ActiveProfileScreen.kt @@ -1,5 +1,8 @@ package mobi.giza.compose.ui.composable +import mobi.giza.compose.ui.composable.navigation.routes.DisappearingMessagesRoute +import mobi.giza.compose.resources.disappearing_messages +import androidx.compose.material.icons.filled.HourglassBottom import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row @@ -375,6 +378,29 @@ fun ActiveProfileScreen( } } + // How long what this profile writes in NIP-17 conversations lasts. + // docs/disappearing-messages.md, Phase 6. + if (canSign) item { + TextButton( + onClick = { + onNavigateToRoute.invoke( + DisappearingMessagesRoute(activeUserPublicKey = activeUserPublicKey) + ) + } + ) { + Icon( + Icons.Default.HourglassBottom, + contentDescription = Decorative + ) + + Spacer( + modifier = Modifier.width(MaterialTheme.spacing.space125) + ) + + Text(stringResource(Res.string.disappearing_messages)) + } + } + item { TextButton( onClick = { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt index 7ed88db6..16b0f121 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt @@ -9,6 +9,12 @@ import mobi.giza.compose.resources.no_groups_have_been_made_in_this_conversation import mobi.giza.compose.resources.groups import mobi.giza.compose.ui.composable.navigation.routes.DkgRitualRoute import mobi.giza.compose.repository.GroupMadeHere +import mobi.giza.compose.ui.composable.navigation.routes.DisappearingMessagesRoute +import mobi.giza.compose.resources.disappearing_messages +import mobi.giza.compose.resources.disappearing_messages_room_supporting +import androidx.compose.material.icons.filled.HourglassBottom +import androidx.compose.foundation.clickable +import androidx.compose.material3.minimumInteractiveComponentSize import mobi.giza.compose.ui.composable.widgets.LocalCanSign import mobi.giza.compose.resources.propose_event import mobi.giza.compose.ui.composable.navigation.routes.ProposeGroupEventRoute @@ -32,7 +38,6 @@ import androidx.compose.material.icons.filled.Mail import mobi.giza.compose.ui.composable.navigation.routes.ConfederationsRoute import mobi.giza.compose.ui.composable.navigation.routes.GroupDmSetupRoute import mobi.giza.compose.ui.view.state.GroupDmRow -import androidx.compose.material.icons.filled.Mail import mobi.giza.compose.resources.open_the_groups_messages import mobi.giza.compose.resources.group_messages import mobi.giza.compose.resources.this_group_receives_direct_messages @@ -228,7 +233,6 @@ import mobi.giza.compose.resources.rotation_proposing_is_taking_part import mobi.giza.compose.resources.rotation_taking_part import mobi.giza.compose.resources.rotation_no_key import mobi.giza.compose.ui.view.state.RotationPreview -import androidx.compose.runtime.remember import mobi.giza.compose.resources.waiting_on_s_since_s import mobi.giza.compose.resources.rotation_ended import mobi.giza.compose.resources.abandon_rotation_body @@ -607,6 +611,24 @@ fun ChatRoomDetailScreen( } } + // How long what the user writes here lasts. Local, like muting, and only in + // a NIP-17 room: an MLS room follows the group's own retention. + // docs/disappearing-messages.md, D4. + if (chatRoomDetailUIState.localChatRoom.chatRoom.mlsGroupState == null) item(key = "disappearing") { + val room = chatRoomDetailUIState.localChatRoom.chatRoom + ListItem( + modifier = Modifier.minimumInteractiveComponentSize().clickable { + onNavigateToRoute.invoke(DisappearingMessagesRoute(activeUserPublicKey, room.id)) + }, + leadingContent = { Icon(Icons.Default.HourglassBottom, contentDescription = Decorative) }, + headlineContent = { Text(stringResource(Res.string.disappearing_messages)) }, + // The fixed description, not the current length: this screen reads the + // room once, so a length shown here would be stale after a change. + supportingContent = { Text(stringResource(Res.string.disappearing_messages_room_supporting)) }, + trailingContent = { Icon(Icons.Default.ChevronRight, contentDescription = Decorative) }, + ) + } + // Directly under the signing key, because between them // they are what the room *is*: the identity it signs as // and whose child it is. Absent on a group that is diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt index 9063786e..9d1ab5bb 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt @@ -1,5 +1,9 @@ package mobi.giza.compose.ui.composable +import androidx.compose.runtime.remember +import mobi.giza.compose.GizaRuntime +import mobi.giza.compose.database.repository.DisappearingSettingsStore +import mobi.giza.compose.ui.composable.navigation.routes.DisappearingMessagesRoute import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box @@ -104,6 +108,10 @@ fun ChatRoomMessagingScreen( * phone the same screen is a destination, and the button is what leaves it. */ onNavigateBack: (() -> Unit)?, + /** How long what the user writes here lasts (docs/disappearing-messages.md, D12); none in a preview. */ + disappearingSettings: DisappearingSettingsStore? = remember { + GizaRuntime.current()?.let { DisappearingSettingsStore(it.auxDatabaseManager.auxDatabase) } + }, ) { val chatRoomMessagingViewModel: ChatRoomMessagingViewModel = viewModel( factory = ChatRoomMessagingViewModel.factory( @@ -163,6 +171,12 @@ fun ChatRoomMessagingScreen( if (onNavigateBack != null) NavigateBackButton(onNavigateBack) }, actions = { + // A NIP-17 conversation's timer: an MLS room follows the group's own retention. + if (disappearingSettings != null && chatRoomDetailUIState.localChatRoom.chatRoom.mlsGroupState == null) { + DisappearingTimerAction(chatRoomId, activeUserPublicKey, disappearingSettings) { + onNavigateToRoute.invoke(DisappearingMessagesRoute(activeUserPublicKey, chatRoomId)) + } + } IconButton( onClick = { // Navigate to the invite user screen... @@ -201,6 +215,11 @@ fun ChatRoomMessagingScreen( ) } + if (disappearingSettings != null && chatRoomDetailUIState.localChatRoom.chatRoom.mlsGroupState == null) { + DisappearingNotice(chatRoomId, activeUserPublicKey, disappearingSettings) { + onNavigateToRoute.invoke(DisappearingMessagesRoute(activeUserPublicKey, chatRoomId)) + } + } Column( modifier = Modifier.weight(1f).fillMaxWidth() ) { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/DisappearingMessagesScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/DisappearingMessagesScreen.kt new file mode 100644 index 00000000..1ae11135 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/DisappearingMessagesScreen.kt @@ -0,0 +1,375 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.HourglassBottom +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Card +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SegmentedButton +import androidx.compose.material3.SegmentedButtonDefaults +import androidx.compose.material3.SingleChoiceSegmentedButtonRow +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import kotlin.time.Clock +import kotlin.time.Instant +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.launch +import mobi.giza.compose.database.repository.DisappearingSettingsStore +import mobi.giza.compose.extensions.toFormattedTimeAndDateString +import mobi.giza.compose.nostr.DisappearingMessages +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.cancel +import mobi.giza.compose.resources.disappearing_custom +import mobi.giza.compose.resources.disappearing_custom_amount +import mobi.giza.compose.resources.disappearing_custom_out_of_range +import mobi.giza.compose.resources.disappearing_custom_title +import mobi.giza.compose.resources.disappearing_default_value +import mobi.giza.compose.resources.disappearing_explanation +import mobi.giza.compose.resources.disappearing_groups_note +import mobi.giza.compose.resources.disappearing_messages +import mobi.giza.compose.resources.disappearing_notice +import mobi.giza.compose.resources.disappearing_notice_change +import mobi.giza.compose.resources.disappearing_notice_dismiss +import mobi.giza.compose.resources.disappearing_off +import mobi.giza.compose.resources.disappearing_offline_warning +import mobi.giza.compose.resources.disappearing_protocol_note +import mobi.giza.compose.resources.disappearing_saved +import mobi.giza.compose.resources.disappearing_set +import mobi.giza.compose.resources.disappearing_timer_description +import mobi.giza.compose.resources.disappearing_unit_days +import mobi.giza.compose.resources.disappearing_unit_hours +import mobi.giza.compose.resources.disappearing_unit_minutes +import mobi.giza.compose.resources.disappearing_use_default +import mobi.giza.compose.resources.disappears_at +import mobi.giza.compose.resources.duration_days +import mobi.giza.compose.resources.duration_hours +import mobi.giza.compose.resources.duration_minutes +import mobi.giza.compose.resources.duration_one_day +import mobi.giza.compose.resources.duration_one_hour +import mobi.giza.compose.resources.duration_one_minute +import mobi.giza.compose.resources.duration_one_week +import mobi.giza.compose.resources.duration_weeks +import mobi.giza.compose.ui.composable.widgets.Decorative +import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator +import mobi.giza.compose.ui.composable.widgets.NavigateBackButton +import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition +import mobi.giza.compose.ui.composable.widgets.rememberNotifier +import mobi.giza.compose.ui.theme.readableContent +import mobi.giza.compose.ui.theme.spacing +import org.jetbrains.compose.resources.getString +import org.jetbrains.compose.resources.stringResource + +/** + * A length as a person reads it: the largest unit that divides it exactly, so a preset reads + * "1 week" and a custom ninety minutes reads "90 minutes". Off is "Off". + */ +@Composable +fun disappearingLengthText(seconds: Long): String { + val (unit, count) = DisappearingLength.split(seconds) ?: return stringResource(Res.string.disappearing_off) + return when (unit) { + DisappearingLength.Unit.WEEKS -> if (count == 1L) stringResource(Res.string.duration_one_week) else stringResource(Res.string.duration_weeks, count) + DisappearingLength.Unit.DAYS -> if (count == 1L) stringResource(Res.string.duration_one_day) else stringResource(Res.string.duration_days, count) + DisappearingLength.Unit.HOURS -> if (count == 1L) stringResource(Res.string.duration_one_hour) else stringResource(Res.string.duration_hours, count) + DisappearingLength.Unit.MINUTES -> if (count == 1L) stringResource(Res.string.duration_one_minute) else stringResource(Res.string.duration_minutes, count) + } +} + +/** The arithmetic under [disappearingLengthText] and the custom dialog, kept out of composition so it can be tested. */ +object DisappearingLength { + enum class Unit(val seconds: Long) { + MINUTES(DisappearingMessages.MINUTE), + HOURS(DisappearingMessages.HOUR), + DAYS(DisappearingMessages.DAY), + WEEKS(7 * DisappearingMessages.DAY), + } + + /** The largest unit [seconds] is a whole number of, and how many; null for Off. */ + fun split(seconds: Long): Pair? { + if (seconds <= 0) return null + val unit = Unit.entries.reversed().firstOrNull { seconds % it.seconds == 0L } ?: Unit.MINUTES + return unit to seconds / unit.seconds + } + + /** A custom length from what was typed, or null when it is not a whole number in bounds. */ + fun parse(amount: String, unit: Unit): Long? { + val count = amount.trim().toLongOrNull() ?: return null + if (count <= 0 || count > DisappearingMessages.MAX_SECONDS / unit.seconds) return null + return (count * unit.seconds).takeIf { DisappearingMessages.isValidPolicy(it) } + } +} + +private sealed interface DisappearingUIState { + data object Loading : DisappearingUIState + + /** [selected] is null when a conversation follows the default; [default] is the identity's. */ + data class Loaded(val selected: Long?, val default: Long) : DisappearingUIState +} + +/** + * How long what the user writes lasts: their default, or with [chatRoomId] one conversation's + * override, which may also go back to following the default. docs/disappearing-messages.md, D3, + * D4, D7 and D11. + * + * No error or empty state: the value is one row of the local database with a default when absent, + * and a read that fails there has failed for every screen in the app. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun DisappearingMessagesScreen( + activeUserPublicKey: String, + chatRoomId: String?, + store: DisappearingSettingsStore, + onNavigateBack: () -> Unit, +) { + val state by remember(activeUserPublicKey, chatRoomId) { + if (chatRoomId == null) { + store.observeDefault(activeUserPublicKey).map { default -> DisappearingUIState.Loaded(default, default) } + } else { + combine(store.observeOverride(chatRoomId), store.observeDefault(activeUserPublicKey)) { override, default -> + DisappearingUIState.Loaded(override, default) + } + } + }.collectAsState(initial = DisappearingUIState.Loading) + + val scope = rememberCoroutineScope() + val notify = rememberNotifier(scope) + var customOpen by remember { mutableStateOf(false) } + + fun save(seconds: Long?, label: String) { + scope.launch { + if (chatRoomId == null) store.saveDefault(activeUserPublicKey, seconds ?: DisappearingMessages.DEFAULT_SECONDS) + else store.saveOverride(chatRoomId, seconds) + notify(getString(Res.string.disappearing_saved, label)) + } + } + + Scaffold( + topBar = { + TopAppBar( + title = { Text(stringResource(Res.string.disappearing_messages)) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + }, + ) { innerPadding -> + Column(modifier = Modifier.padding(innerPadding).readableContent()) { + ScreenStateTransition(state) { uiState -> + when (uiState) { + DisappearingUIState.Loading -> LoadingDataIndicator() + is DisappearingUIState.Loaded -> { + val defaultLabel = disappearingLengthText(uiState.default) + val isCustom = uiState.selected != null && uiState.selected !in DisappearingMessages.PRESETS + LazyColumn(modifier = Modifier.selectableGroup()) { + if (chatRoomId != null) item { + val label = stringResource(Res.string.disappearing_use_default, defaultLabel) + ChoiceRow(label, selected = uiState.selected == null) { save(null, defaultLabel) } + } + DisappearingMessages.PRESETS.forEach { preset -> + item(key = preset) { + val label = disappearingLengthText(preset) + ChoiceRow(label, selected = uiState.selected == preset) { save(preset, label) } + } + } + item { + ChoiceRow( + label = stringResource(Res.string.disappearing_custom), + selected = isCustom, + supporting = if (isCustom) disappearingLengthText(uiState.selected!!) else null, + ) { customOpen = true } + } + item { + Column( + modifier = Modifier.padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + Explanation(stringResource(Res.string.disappearing_explanation)) + Explanation(stringResource(Res.string.disappearing_offline_warning)) + Explanation(stringResource(Res.string.disappearing_protocol_note)) + Explanation(stringResource(Res.string.disappearing_groups_note)) + } + } + } + if (customOpen) { + CustomLengthDialog( + initial = uiState.selected?.takeIf { isCustom }, + onDismiss = { customOpen = false }, + onSet = { seconds, label -> + customOpen = false + save(seconds, label) + }, + ) + } + } + } + } + } + } +} + +@Composable +private fun Explanation(text: String) = Text( + text = text, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, +) + +/** A radio row chosen from anywhere on it: the row is the target, at the list item's height. */ +@Composable +private fun ChoiceRow(label: String, selected: Boolean, supporting: String? = null, onSelect: () -> Unit) { + ListItem( + modifier = Modifier.selectable(selected = selected, role = Role.RadioButton, onClick = onSelect), + leadingContent = { RadioButton(selected = selected, onClick = null) }, + headlineContent = { Text(label) }, + supportingContent = supporting?.let { { Text(it) } }, + ) +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun CustomLengthDialog(initial: Long?, onDismiss: () -> Unit, onSet: (Long, String) -> Unit) { + val start = initial?.let { DisappearingLength.split(it) } + ?.let { (unit, count) -> if (unit == DisappearingLength.Unit.WEEKS) DisappearingLength.Unit.DAYS to count * 7 else unit to count } + var amount by remember { mutableStateOf(start?.second?.toString() ?: "") } + var unit by remember { mutableStateOf(start?.first ?: DisappearingLength.Unit.HOURS) } + val parsed = DisappearingLength.parse(amount, unit) + val showError = amount.isNotBlank() && parsed == null + val label = parsed?.let { disappearingLengthText(it) } + val units = listOf( + DisappearingLength.Unit.MINUTES to stringResource(Res.string.disappearing_unit_minutes), + DisappearingLength.Unit.HOURS to stringResource(Res.string.disappearing_unit_hours), + DisappearingLength.Unit.DAYS to stringResource(Res.string.disappearing_unit_days), + ) + + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(Res.string.disappearing_custom_title)) }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)) { + OutlinedTextField( + value = amount, + onValueChange = { amount = it.filter(Char::isDigit).take(6) }, + label = { Text(stringResource(Res.string.disappearing_custom_amount)) }, + singleLine = true, + isError = showError, + supportingText = { if (showError) Text(stringResource(Res.string.disappearing_custom_out_of_range)) }, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + modifier = Modifier.fillMaxWidth(), + ) + SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { + units.forEachIndexed { index, (option, text) -> + SegmentedButton( + selected = unit == option, + onClick = { unit = option }, + shape = SegmentedButtonDefaults.itemShape(index, units.size), + ) { Text(text) } + } + } + } + }, + confirmButton = { + TextButton(onClick = { if (parsed != null && label != null) onSet(parsed, label) }, enabled = parsed != null) { + Text(stringResource(Res.string.disappearing_set)) + } + }, + dismissButton = { + TextButton(onClick = onDismiss) { Text(stringResource(Res.string.cancel)) } + }, + ) +} + +/** + * The hourglass beside an expiring line's time. Its description carries what the icon shows and + * the text beside it does not: when the line goes (D12). + */ +@Composable +fun DisappearsIcon(expiresAt: Instant) { + Icon( + Icons.Default.HourglassBottom, + contentDescription = stringResource(Res.string.disappears_at, expiresAt.toFormattedTimeAndDateString()), + modifier = Modifier.size(MaterialTheme.typography.labelSmall.lineHeight.value.dp), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) +} + +/** + * The conversation's timer in its app bar (D12), opening its setting; nothing while the policy in + * force is Off. + */ +@Composable +fun DisappearingTimerAction(chatRoomId: String, userPublicKey: String, store: DisappearingSettingsStore, onOpen: () -> Unit) { + val policy by remember(chatRoomId, userPublicKey) { + combine(store.observeOverride(chatRoomId), store.observeDefault(userPublicKey)) { override, default -> + DisappearingMessages.policyFor(override, default) + } + }.collectAsState(initial = DisappearingMessages.OFF) + if (policy == DisappearingMessages.OFF) return + IconButton(onClick = onOpen) { + Icon( + Icons.Default.HourglassBottom, + contentDescription = stringResource(Res.string.disappearing_timer_description, disappearingLengthText(policy)), + ) + } +} + +/** + * The one-time notice that what the user writes in this conversation now disappears (D9). Shown + * until dismissed or acted on, once per conversation, and only while a policy is in force. + */ +@Composable +fun DisappearingNotice(chatRoomId: String, userPublicKey: String, store: DisappearingSettingsStore, onChange: () -> Unit) { + val scope = rememberCoroutineScope() + val shown by remember(chatRoomId) { store.observeNoticeShown(chatRoomId) }.collectAsState(initial = true) + val policy by remember(chatRoomId, userPublicKey) { + combine(store.observeOverride(chatRoomId), store.observeDefault(userPublicKey)) { override, default -> + DisappearingMessages.policyFor(override, default) + } + }.collectAsState(initial = DisappearingMessages.OFF) + if (shown || policy == DisappearingMessages.OFF) return + + fun dismiss() = scope.launch { store.markNoticeShown(chatRoomId, Clock.System.now()) } + + Card(modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.compactPadding)) { + Column( + modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap), + ) { + Row(horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { + Icon(Icons.Default.HourglassBottom, contentDescription = Decorative) + Text(stringResource(Res.string.disappearing_notice, disappearingLengthText(policy))) + } + Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + TextButton(onClick = { dismiss(); onChange() }) { Text(stringResource(Res.string.disappearing_notice_change)) } + TextButton(onClick = { dismiss() }) { Text(stringResource(Res.string.disappearing_notice_dismiss)) } + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt index 0780d0af..c616211e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt @@ -1,5 +1,8 @@ package mobi.giza.compose.ui.composable.navigation +import mobi.giza.compose.ui.composable.navigation.routes.DisappearingMessagesRoute +import mobi.giza.compose.ui.composable.DisappearingMessagesScreen +import mobi.giza.compose.database.repository.DisappearingSettingsStore import mobi.giza.compose.ui.composable.navigation.routes.ProposeGroupEventRoute import mobi.giza.compose.ui.composable.ProposeGroupEventScreen import mobi.giza.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute @@ -220,6 +223,7 @@ fun GizaNavHost( val notaryViewModel: NotaryViewModel = runtime.notary val synchronizationViewModel: SynchronizationViewModel = runtime.synchronization remember(runtime) { runtime.notifications } + remember(runtime) { runtime.disappearing } // TODO: Produce a synchronization UI element... @@ -929,6 +933,15 @@ fun GizaNavHost( onNavigateBack = { navController.popBackStack() }, ) } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + DisappearingMessagesScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + store = remember(runtime) { DisappearingSettingsStore(runtime.auxDatabaseManager.auxDatabase) }, + onNavigateBack = { navController.popBackStack() }, + ) + } composable { backStackEntry -> val route = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/DisappearingMessagesRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/DisappearingMessagesRoute.kt new file mode 100644 index 00000000..2ef67a42 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/DisappearingMessagesRoute.kt @@ -0,0 +1,13 @@ +package mobi.giza.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** + * How long what the user writes lasts: their default when [chatRoomId] is null, else that + * conversation's override. docs/disappearing-messages.md, Phase 6. + */ +@Serializable +data class DisappearingMessagesRoute( + val activeUserPublicKey: String, + val chatRoomId: String? = null, +): Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt index e49a292e..8e56dfa9 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt @@ -1,5 +1,6 @@ package mobi.giza.compose.ui.composable.widgets.chat +import mobi.giza.compose.ui.composable.DisappearsIcon import androidx.compose.material.icons.filled.Warning import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement @@ -522,6 +523,7 @@ fun ChatTranscript( text = localChatMessage.chatMessage.createdAt.toFormattedTimeAndDateString(), style = MaterialTheme.typography.labelSmall ) + localChatMessage.chatMessage.expiresAt?.let { DisappearsIcon(it) } if (localChatMessage.chatMessage.isUserMessage) { if (localChatMessage.chatMessageBroadcastNostrEventReceiptRelation != null) { Icon( diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/DisappearingMessagesTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/DisappearingMessagesTest.kt new file mode 100644 index 00000000..a1b99b88 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/DisappearingMessagesTest.kt @@ -0,0 +1,162 @@ +package mobi.giza.compose.nostr + +import com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent +import com.vitorpamplona.quartz.nip17Dm.messages.ChatMessageEvent +import mobi.giza.compose.nostr.DisappearingMessages.DAY +import mobi.giza.compose.nostr.DisappearingMessages.ExpiryClass +import mobi.giza.compose.nostr.DisappearingMessages.HOUR +import mobi.giza.compose.nostr.DisappearingMessages.OFF +import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents +import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents +import mobi.giza.compose.nostr.dkg.DkgRitualEvents +import mobi.giza.compose.nostr.frost.FrostSigningEvents +import mobi.giza.compose.nostr.frost.ShareRefreshEvents +import mobi.giza.compose.nostr.frost.ShareRepairEvents +import mobi.giza.compose.nostr.groupdm.GroupEcdhEvents +import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** docs/disappearing-messages.md, D2 to D5: the rules, without a database. */ +class DisappearingMessagesTest { + + private val createdAt = 1_800_000_000L + private val chat = ChatMessageEvent.KIND + + /** + * Every kind Giza is known to put in a NIP-17 wrap, or in a ceremony that could. A kind missing + * here falls through to the unclassified floor, which still expires but was nobody's decision; + * classifying it means adding it to `DisappearingMessages` with a reason, and then here. + */ + private val knownProtocolKinds = + DkgRitualEvents.ALL + FrostSigningEvents.ALL + ConfederationRitualEvents.ALL + ConfederationSigningEvents.ALL + + InboxKeyRitualEvents.ALL + ShareRefreshEvents.ALL + ShareRepairEvents.ALL + GroupEcdhEvents.ALL + + ConfederationKinds.ALL + setOf(WelcomeEvent.KIND) + + @Test + fun `every kind the app sends is classified on purpose`() { + val unclassified = knownProtocolKinds.filter { (DisappearingMessages.classOf(it) as? ExpiryClass.Protocol)?.classified == false } + assertEquals(emptyList(), unclassified) + DisappearingMessages.WRITTEN_KINDS.forEach { assertSame(ExpiryClass.Written, DisappearingMessages.classOf(it)) } + } + + @Test + fun `a kind nobody classified still expires, after a week`() { + val expiryClass = DisappearingMessages.classOf(99_999) + assertEquals(ExpiryClass.Protocol(DisappearingMessages.UNCLASSIFIED_FLOOR, classified = false), expiryClass) + assertEquals(createdAt + 7 * DAY, DisappearingMessages.expiryFor(99_999, createdAt, OFF, emptyArray())) + } + + @Test + fun `what a person writes follows the policy, and Off means no expiry`() { + assertEquals(createdAt + DAY, DisappearingMessages.expiryFor(chat, createdAt, DAY, emptyArray())) + assertEquals(createdAt + HOUR, DisappearingMessages.expiryFor(chat, createdAt, HOUR, emptyArray())) + assertNull(DisappearingMessages.expiryFor(chat, createdAt, OFF, emptyArray())) + } + + @Test + fun `a protocol message expires even with the policy Off, at its floor`() { + val nonce = FrostSigningEvents.NONCE + assertEquals(createdAt + DisappearingMessages.SIGNING_FLOOR, DisappearingMessages.expiryFor(nonce, createdAt, OFF, emptyArray())) + assertEquals(createdAt + DisappearingMessages.SIGNING_FLOOR, DisappearingMessages.expiryFor(nonce, createdAt, HOUR, emptyArray())) + assertEquals(createdAt + 7 * DAY, DisappearingMessages.expiryFor(DkgRitualEvents.ROUND_1, createdAt, DAY, emptyArray())) + assertEquals(createdAt + 7 * DAY, DisappearingMessages.expiryFor(WelcomeEvent.KIND, createdAt, OFF, emptyArray())) + } + + @Test + fun `a policy longer than the floor wins`() { + assertEquals(createdAt + 28 * DAY, DisappearingMessages.expiryFor(DkgRitualEvents.ROUND_1, createdAt, 28 * DAY, emptyArray())) + } + + @Test + fun `a rumor that carries an expiry keeps it and gets no second one`() { + val proposalLapses = createdAt + 3 * DAY + val tags = arrayOf(arrayOf("p", "a".repeat(64)), arrayOf("expiration", proposalLapses.toString())) + assertEquals(proposalLapses, DisappearingMessages.expiryFor(ConfederationKinds.PROPOSAL, createdAt, DAY, tags)) + val stamped = DisappearingMessages.stamp(ConfederationKinds.PROPOSAL, createdAt, DAY, tags) + assertSame(tags, stamped) + assertEquals(1, stamped.count { it[0] == "expiration" }) + } + + @Test + fun `stamping appends one tag, after the others`() { + val tags = arrayOf(arrayOf("p", "b".repeat(64))) + val stamped = DisappearingMessages.stamp(chat, createdAt, DAY, tags) + assertEquals(2, stamped.size) + assertEquals(listOf("p", "b".repeat(64)), stamped[0].toList()) + assertEquals(listOf("expiration", (createdAt + DAY).toString()), stamped[1].toList()) + assertSame(tags, DisappearingMessages.stamp(chat, createdAt, OFF, tags)) + } + + @Test + fun `the wrap expires later than the rumor by at most two days, never earlier`() { + val rumorExpiry = createdAt + DAY + // A wrap dated anywhere in the two days before the rumor, as quartz's randomization does. + listOf(0L, 1L, HOUR, DAY, 2 * DAY - 1, 2 * DAY).forEach { pushedBack -> + val wrapExpiry = DisappearingMessages.wrapExpiration(rumorExpiry, createdAt, createdAt - pushedBack)!! + assertTrue(wrapExpiry >= rumorExpiry, "pushed back $pushedBack: $wrapExpiry < $rumorExpiry") + assertTrue(wrapExpiry <= rumorExpiry + 2 * DAY, "pushed back $pushedBack: $wrapExpiry too late") + } + } + + @Test + fun `a rumor with no expiry gives a wrap with none`() { + assertNull(DisappearingMessages.wrapExpiration(null, createdAt, createdAt - HOUR)) + assertNull(DisappearingMessages.wrapExpiration(createdAt, createdAt, createdAt - HOUR)) + } + + @Test + fun `a malformed expiry reads as none`() { + assertNull(DisappearingMessages.expirationOf(arrayOf(arrayOf("expiration", "soon")))) + assertNull(DisappearingMessages.expirationOf(arrayOf(arrayOf("expiration")))) + assertNull(DisappearingMessages.expirationOf(arrayOf(arrayOf("expiration", createdAt.toString())), createdAt)) + assertNull(DisappearingMessages.expirationOf(arrayOf(arrayOf("expiration", (createdAt - 1).toString())), createdAt)) + assertEquals(createdAt + 1, DisappearingMessages.expirationOf(arrayOf(arrayOf("expiration", (createdAt + 1).toString())), createdAt)) + } + + @Test + fun `the policy bounds`() { + assertTrue(DisappearingMessages.isValidPolicy(OFF)) + assertTrue(DisappearingMessages.isValidPolicy(DisappearingMessages.MIN_SECONDS)) + assertTrue(DisappearingMessages.isValidPolicy(DisappearingMessages.MAX_SECONDS)) + assertFalse(DisappearingMessages.isValidPolicy(DisappearingMessages.MIN_SECONDS - 1)) + assertFalse(DisappearingMessages.isValidPolicy(DisappearingMessages.MAX_SECONDS + 1)) + assertFalse(DisappearingMessages.isValidPolicy(-1)) + DisappearingMessages.PRESETS.forEach { assertTrue(DisappearingMessages.isValidPolicy(it)) } + assertEquals(DAY, DisappearingMessages.DEFAULT_SECONDS) + } + + @Test + fun `the override wins over the default, and null follows it`() { + assertEquals(DAY, DisappearingMessages.policyFor(null, DAY)) + assertEquals(OFF, DisappearingMessages.policyFor(OFF, DAY)) + assertEquals(HOUR, DisappearingMessages.policyFor(HOUR, DAY)) + } + + @Test + fun `a signer accepts no expiry or a choosable one, and nothing else`() { + assertTrue(DisappearingMessages.isAcceptableExpiry(emptyArray(), createdAt)) + assertTrue(DisappearingMessages.isAcceptableExpiry(arrayOf(arrayOf("expiration", (createdAt + DAY).toString())), createdAt)) + assertFalse(DisappearingMessages.isAcceptableExpiry(arrayOf(arrayOf("expiration", (createdAt + 1).toString())), createdAt)) + assertFalse(DisappearingMessages.isAcceptableExpiry(arrayOf(arrayOf("expiration", (createdAt + 400 * DAY).toString())), createdAt)) + assertFalse(DisappearingMessages.isAcceptableExpiry(arrayOf(arrayOf("expiration", "soon")), createdAt)) + } + + @Test + fun `an expiry is read off a rumor kept as JSON`() { + val json = """{"id":"","pubkey":"${"a".repeat(64)}","created_at":$createdAt,"kind":14,"tags":[["expiration","${createdAt + HOUR}"]],"content":"hi"}""" + assertEquals(createdAt + HOUR, DisappearingMessages.expirationOfRumorJson(json)) + assertNull(DisappearingMessages.expirationOfRumorJson("not json")) + } + + @Test + fun `expired from its expiry on`() { + assertFalse(DisappearingMessages.isExpired(createdAt, createdAt - 1)) + assertTrue(DisappearingMessages.isExpired(createdAt, createdAt)) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/DisappearingMessagesMigrationJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/DisappearingMessagesMigrationJvmTest.kt new file mode 100644 index 00000000..3adafb6b --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/DisappearingMessagesMigrationJvmTest.kt @@ -0,0 +1,183 @@ +package mobi.giza.compose.database.migrations + +import androidx.room3.Room +import androidx.sqlite.SQLiteConnection +import androidx.sqlite.driver.bundled.BundledSQLiteDriver +import androidx.sqlite.execSQL +import java.io.File +import java.nio.file.Files +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Instant +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.booleanOrNull +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ExpiredGiftWrap +import mobi.giza.compose.database.repository.DisappearingSettingsStore +import mobi.giza.compose.nostr.DisappearingMessages + +/** + * 49 -> 50: disappearing messages' storage arrives empty, and an upgraded identity reads as the + * one-day default without a data step. docs/disappearing-messages.md, Phase 2 and D9. + * + * Built from the exported v49 schema, as [ReadMarkMigrationJvmTest] builds its v47. + */ +class DisappearingMessagesMigrationJvmTest { + + private val directory: File = Files.createTempDirectory("giza-disappearing").toFile() + private val file: File = File(directory, "aux.db") + + @AfterTest + fun cleanUp() { + directory.deleteRecursively() + } + + private val schemas: File = + (File("schemas").takeIf { it.isDirectory } ?: File("composeApp/schemas")) + .resolve("mobi.giza.compose.database.GizaDatabase") + + private fun schema(version: Int): JsonObject = + Json.parseToJsonElement(schemas.resolve("$version.json").readText()).jsonObject["database"]!!.jsonObject + + private fun entities(version: Int) = schema(version)["entities"]!!.jsonArray.map { it.jsonObject } + + private val user = "f".repeat(64) + private val nip17Room = "a".repeat(64) + private val payload = "b".repeat(64) + + private fun writeV49() { + BundledSQLiteDriver().open(file.absolutePath).use { connection -> + entities(49).forEach { entity -> + val table = entity["tableName"]!!.jsonPrimitive.content + connection.execSQL(entity["createSql"]!!.jsonPrimitive.content.replace("\${TABLE_NAME}", table)) + entity["indices"]?.jsonArray.orEmpty().forEach { index -> + connection.execSQL(index.jsonObject["createSql"]!!.jsonPrimitive.content.replace("\${TABLE_NAME}", table)) + } + } + schema(49)["setupQueries"]!!.jsonArray.forEach { connection.execSQL(it.jsonPrimitive.content) } + connection.execSQL("PRAGMA user_version = 49") + + insert(connection, "NostrEvent", mapOf("id" to "e".repeat(64), "pubKey" to user)) + insert(connection, "Profile", mapOf("publicKey" to user, "nostrEventId" to "e".repeat(64))) + insert(connection, "ChatRoom", mapOf("id" to nip17Room, "userPublicKey" to user, "mlsGroupState" to null, "initialGiftWrapPayloadId" to null)) + insert( + connection, + "GiftWrapPayload", + mapOf("id" to payload, "publicKey" to user, "chatRoomId" to nip17Room, "kind" to 14L, "giftWrapSealId" to null), + ) + insert( + connection, + "ChatMessage", + mapOf( + "id" to 1L, + "chatRoomId" to nip17Room, + "giftWrapPayloadId" to payload, + "marmotGroupEventId" to null, + "marmotInnerEventId" to null, + ), + ) + } + } + + /** A row with [values], every other NOT NULL column without a default given a placeholder. */ + private fun insert(connection: SQLiteConnection, table: String, values: Map) { + val entity = entities(49).single { it["tableName"]!!.jsonPrimitive.content == table } + val filled = LinkedHashMap() + entity["fields"]!!.jsonArray.map { it.jsonObject }.forEach { field -> + val column = field["columnName"]!!.jsonPrimitive.content + val notNull = field["notNull"]?.jsonPrimitive?.booleanOrNull == true + when { + column in values -> filled[column] = values[column] + notNull && field["defaultValue"] == null -> filled[column] = when (field["affinity"]!!.jsonPrimitive.content) { + "TEXT" -> if (column == "tags") "[]" else "x" + "BLOB" -> ByteArray(0) + else -> 1L + } + } + } + val sql = "INSERT INTO `$table` (${filled.keys.joinToString(", ") { "`$it`" }}) " + + "VALUES (${filled.keys.joinToString(", ") { "?" }})" + connection.prepare(sql).use { statement -> + filled.values.forEachIndexed { position, value -> + val index = position + 1 + when (value) { + null -> statement.bindNull(index) + is String -> statement.bindText(index, value) + is ByteArray -> statement.bindBlob(index, value) + is Long -> statement.bindLong(index, value) + else -> error("no binding for a ${value::class.simpleName}") + } + } + statement.step() + } + } + + @Test + fun `an upgraded install keeps its messages, has no expiries, and defaults to a day`(): Unit = runBlocking { + writeV49() + + val database = getRoomDatabase(Room.databaseBuilder(name = file.absolutePath)) + try { + val room = assertNotNull(database.chatRoomDao().findChatRoomById(nip17Room)).chatRoom + assertNull(room.disappearingMessageSecs, "an upgraded room was given an override") + assertNull(room.disappearingNoticeShownAt, "the one-time notice counts as shown") + + val line = assertNotNull(database.chatMessageDao().getChatMessagesByGiftWrapPayloadId(payload)) + assertNull(line.expiresAt, "a message sent before the upgrade was given an expiry") + assertNull(assertNotNull(database.giftWrapPayloadDao().getById(payload)).expiresAt) + + val store = DisappearingSettingsStore(database) + assertNull(database.disappearingDao().getDefault(user), "an upgrade wrote a setting") + assertEquals(DisappearingMessages.DEFAULT_SECONDS, store.defaultFor(user)) + assertEquals(DisappearingMessages.DEFAULT_SECONDS, store.policyFor(nip17Room, user)) + } finally { + database.close() + } + } + + @Test + fun `the override wins, Off is a value, and the default can change`(): Unit = runBlocking { + writeV49() + + val database = getRoomDatabase(Room.databaseBuilder(name = file.absolutePath)) + try { + val store = DisappearingSettingsStore(database) + store.saveDefault(user, DisappearingMessages.HOUR) + assertEquals(DisappearingMessages.HOUR, store.policyFor(nip17Room, user)) + store.saveOverride(nip17Room, DisappearingMessages.OFF) + assertEquals(DisappearingMessages.OFF, store.policyFor(nip17Room, user)) + store.saveOverride(nip17Room, null) + assertEquals(DisappearingMessages.HOUR, store.policyFor(nip17Room, user)) + } finally { + database.close() + } + } + + @Test + fun `a tombstone lasts until its wrap would have`(): Unit = runBlocking { + writeV49() + + val database = getRoomDatabase(Room.databaseBuilder(name = file.absolutePath)) + try { + val dao = database.disappearingDao() + dao.tombstone(ExpiredGiftWrap("c".repeat(64), Instant.fromEpochSeconds(2_000))) + assertTrue(dao.isTombstoned("c".repeat(64))) + assertEquals(0, dao.pruneTombstones(Instant.fromEpochSeconds(1_999))) + assertEquals(1, dao.pruneTombstones(Instant.fromEpochSeconds(2_000))) + assertFalse(dao.isTombstoned("c".repeat(64))) + } finally { + database.close() + } + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt index f3d9f509..7033e8c7 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt @@ -70,10 +70,11 @@ class ShippedProfileUpgradeJvmTest { * (Phase 14), 46 for the group's inbox (docs/group-inbox.md, Phase 3), 47 for a group's * direct messages by threshold ECDH (docs/group-threshold-ecdh.md, Phase 4), 48 for * notifications' read marks and ledger (docs/notifications-and-background-sync.md, Phase 3) and - * 49 for the confederation's statements between inboxes (docs/confederation-without-coordinator.md), so - * the upgrade crosses thirteen generated migrations and the file has to come out at the last. + * 49 for the confederation's statements between inboxes (docs/confederation-without-coordinator.md) and + * 50 for disappearing messages (docs/disappearing-messages.md, Phase 2), so the upgrade crosses + * fourteen generated migrations and the file has to come out at the last. */ - private val current = 49 + private val current = 50 private val directory: File = Files.createTempDirectory("giza-shipped-profile").toFile() private val file: File = File(directory, "aux.db") diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/repository/DisappearingSendJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/repository/DisappearingSendJvmTest.kt new file mode 100644 index 00000000..e1b3e56e --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/repository/DisappearingSendJvmTest.kt @@ -0,0 +1,152 @@ +package mobi.giza.compose.database.repository + +import androidx.room3.Room +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlin.time.Instant +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.GiftWrapPayload +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.DisappearingMessages +import mobi.giza.compose.nostr.DisappearingMessages.DAY +import mobi.giza.compose.nostr.frost.FrostSigningEvents + +/** + * docs/disappearing-messages.md, Phase 3: what a NIP-17 send writes, and what the wrap carries. + * + * Real keys throughout: the room id is derived over the members by secp256k1 point work, and the + * seal is opened again as the recipient to see the rumor they would see. + */ +class DisappearingSendJvmTest { + + private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDb() = db.close() + + private val userKeys = KeyPair() + private val aliceKeys = KeyPair() + private val user = userKeys.pubKey.toHexKey() + private val alice = aliceKeys.pubKey.toHexKey() + + private val repository = DatabaseChatRepository(database = db, scope = CoroutineScope(Dispatchers.Unconfined)) + private val store = DisappearingSettingsStore(db) + + private suspend fun seedProfile(publicKey: String) { + val nostrEventId = publicKey.take(63) + "f" + db.nostrEventDao().upsert(NostrEvent(id = nostrEventId, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = publicKey, userName = "member", nostrEventId = nostrEventId)) + } + + private suspend fun room(): LocalChatRoom { + seedProfile(user) + seedProfile(alice) + return assertNotNull(db.nostrNip17Dao().createNip17ChatRoom(user, listOf(alice))) + } + + private suspend fun onlyPayload(room: LocalChatRoom): GiftWrapPayload = + db.giftWrapPayloadDao().getByChatRoomAndKinds(room.chatRoom.id, listOf(14)).single() + + @Test + fun `a message is stamped a day out by default, and its id covers the tag`() = runBlocking { + val room = room() + repository.sendChatMessage(text = "hello", localChatRoom = room) + + val payload = onlyPayload(room) + val expiry = assertNotNull(DisappearingMessages.expirationOf(payload.tags, payload.createdAt.epochSeconds)) + assertEquals(payload.createdAt.epochSeconds + DAY, expiry) + assertEquals(Instant.fromEpochSeconds(expiry), payload.expiresAt) + assertEquals( + EventHasher.hashId(user, payload.createdAt.epochSeconds, payload.kind, payload.tags, payload.content), + payload.id, + "the payload id is not the id of the rumor the recipient will see", + ) + val line = assertNotNull(db.chatMessageDao().getChatMessagesByGiftWrapPayloadId(payload.id)) + assertEquals(payload.expiresAt, line.expiresAt) + } + + @Test + fun `the conversation's override wins, and Off stamps nothing`() = runBlocking { + val room = room() + store.saveDefault(user, DisappearingMessages.HOUR) + store.saveOverride(room.chatRoom.id, DisappearingMessages.OFF) + repository.sendChatMessage(text = "kept", localChatRoom = room) + + val payload = onlyPayload(room) + assertNull(DisappearingMessages.expirationOf(payload.tags)) + assertNull(payload.expiresAt) + assertNull(assertNotNull(db.chatMessageDao().getChatMessagesByGiftWrapPayloadId(payload.id)).expiresAt) + } + + @Test + fun `a protocol round expires at its floor even with the policy Off`() = runBlocking { + val room = room() + store.saveDefault(user, DisappearingMessages.OFF) + val createdAt = 1_800_000_000L + val tags = store.stamp(room.chatRoom.id, user, FrostSigningEvents.NONCE, createdAt, arrayOf(arrayOf("p", alice))) + assertEquals(createdAt + DisappearingMessages.SIGNING_FLOOR, DisappearingMessages.expirationOf(tags, createdAt)) + } + + @Test + fun `every wrap asks relays to drop it after the rumor, and every seal stays untagged`() = runBlocking { + val room = room() + repository.sendChatMessage(text = "hello", localChatRoom = room) + val payload = onlyPayload(room) + val rumorExpiry = assertNotNull(payload.expiresAt).epochSeconds + + repository.sealGiftWrapPayload(payload, NostrSignerSync(userKeys)) + + val seals = db.giftWrapSealDao().getAllGiftWrapSeals() + assertEquals(2, seals.size, "one seal for alice and one for the sender's own copy") + seals.forEach { seal -> + assertTrue(seal.tags.isEmpty(), "a seal was tagged: ${seal.tags.map { it.toList() }}") + val wrap = assertNotNull(db.nostrEventDao().getNostrEventById(assertNotNull(seal.giftWrapMessageId))) + val wrapExpiry = assertNotNull(DisappearingMessages.expirationOf(wrap.tags), "a wrap carries no expiration") + assertTrue(wrapExpiry >= rumorExpiry, "the wrap would be dropped before the rumor expires") + assertTrue(wrapExpiry <= rumorExpiry + 2 * DAY, "the wrap outlives the rumor by more than two days") + } + + // What alice reads: the rumor, carrying the sender's expiry and nothing merged in from the seal. + val opened = seals.firstNotNullOfOrNull { it.decryptGiftWrapPayload(aliceKeys.privKey!!) } + val rumor = assertNotNull(opened, "alice could not open her seal") + assertEquals(1, rumor.tags.count { it[0] == DisappearingMessages.TAG }) + assertEquals(Instant.fromEpochSeconds(rumorExpiry), rumor.expiresAt) + } + + @Test + fun `a message that expired before it could be sent is not sealed`() = runBlocking { + val room = room() + val createdAt = Clock.System.now().epochSeconds - 2 * DAY + val tags = arrayOf(arrayOf("p", alice), arrayOf(DisappearingMessages.TAG, (createdAt + DAY).toString())) + val payload = GiftWrapPayload( + id = EventHasher.hashId(user, createdAt, 14, tags, "late"), + publicKey = user, + chatRoomId = room.chatRoom.id, + kind = 14, + tags = tags, + content = "late", + createdAt = Instant.fromEpochSeconds(createdAt), + ) + db.giftWrapPayloadDao().upsert(payload) + + repository.sealGiftWrapPayload(payload, NostrSignerSync(userKeys)) + + assertEquals(0, db.giftWrapSealDao().getAllGiftWrapSeals().size, "an expired message was sealed for relays") + assertNull(assertNotNull(db.giftWrapPayloadDao().getById(payload.id)).giftWrapSealId) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/DisappearingGroupMessagesJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/DisappearingGroupMessagesJvmTest.kt new file mode 100644 index 00000000..1a6f2642 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/DisappearingGroupMessagesJvmTest.kt @@ -0,0 +1,108 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.time.Instant +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.GroupDmMessage +import mobi.giza.compose.database.model.GroupDmOutbound +import mobi.giza.compose.database.model.GroupDmWrap +import mobi.giza.compose.database.model.GroupDmWrapState +import mobi.giza.compose.database.model.GroupInboxMessage +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.nostr.DisappearingMessages.DAY +import mobi.giza.compose.nostr.DisappearingMessages.HOUR +import mobi.giza.compose.nostr.confederation.ConfederationKinds + +/** + * docs/disappearing-messages.md, Phase 7: a group's expired messages leave the device with the + * words of the wraps that carried them, and a confederation's statements are left alone. + */ +class DisappearingGroupMessagesJvmTest { + + private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDb() = db.close() + + private val user = KeyPair().pubKey.toHexKey() + private val group = KeyPair().pubKey.toHexKey() + private val alice = KeyPair().pubKey.toHexKey() + private val createdAt = 1_800_000_000L + + private suspend fun seed() { + val nostrEventId = user.take(63) + "f" + db.nostrEventDao().upsert(NostrEvent(id = nostrEventId, pubKey = user, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = user, userName = "member", nostrEventId = nostrEventId)) + db.chatRoomDao().upsert(ChatRoom(id = group, userPublicKey = user, subject = "group", description = null, mlsGroupState = null)) + } + + private fun rumor(kind: Int, from: String, expiry: Long?): Event { + val tags = listOfNotNull(arrayOf("p", alice), expiry?.let { arrayOf("expiration", it.toString()) }).toTypedArray() + return RumorAssembler.assembleRumor(from, EventTemplate(createdAt, kind, tags, "dumela")) + } + + @Test + fun `an expired group message goes, its wrap keeps only its id, and what was owed is dropped`(): Unit = runBlocking { + seed() + val received = rumor(14, alice, createdAt + HOUR) + db.groupDmDao().insertWrap(GroupDmWrap(id = "w".repeat(64), chatRoomId = group, wrapJson = "{ciphertext}", createdAt = Instant.fromEpochSeconds(createdAt), state = GroupDmWrapState.OPENED, sealJson = "{seal}")) + db.groupDmDao().insertMessage( + GroupDmMessage(rumorId = received.id, chatRoomId = group, conversationId = alice, senderPublicKey = alice, rumorJson = received.toJson(), + createdAt = Instant.fromEpochSeconds(createdAt), outgoing = false, wrapId = "w".repeat(64)) + ) + val sent = rumor(14, group, createdAt + HOUR) + db.groupDmDao().insertMessage( + GroupDmMessage(rumorId = sent.id, chatRoomId = group, conversationId = alice, senderPublicKey = group, rumorJson = sent.toJson(), + createdAt = Instant.fromEpochSeconds(createdAt), outgoing = true, signingSessionId = "session") + ) + db.groupDmDao().insertOutbound(GroupDmOutbound(signingSessionId = "session", sealId = "s".repeat(64), chatRoomId = group, recipient = alice, relays = "")) + val kept = rumor(14, alice, null) + db.groupDmDao().insertMessage( + GroupDmMessage(rumorId = kept.id, chatRoomId = group, conversationId = alice, senderPublicKey = alice, rumorJson = kept.toJson(), + createdAt = Instant.fromEpochSeconds(createdAt), outgoing = false) + ) + assertEquals(Instant.fromEpochSeconds(createdAt + HOUR), assertNotNull(db.groupDmDao().getMessage(received.id)).expiresAt) + + DisappearingMessageSweeper.sweep(db, ProtocolRetention, now = Instant.fromEpochSeconds(createdAt + HOUR)) + + assertNull(db.groupDmDao().getMessage(received.id)) + assertNull(db.groupDmDao().getMessage(sent.id)) + assertNotNull(db.groupDmDao().getMessage(kept.id), "a message with no expiry was swept") + val wrap = assertNotNull(db.groupDmDao().getWrap("w".repeat(64)), "the ledger row went, so a re-sync would file it again") + assertEquals("", wrap.wrapJson) + assertNull(wrap.sealJson) + assertEquals(emptyList(), db.groupDmDao().getOutbound("session")) + } + + @Test + fun `an expired inbox reply goes, and a confederation statement stays`(): Unit = runBlocking { + seed() + val reply = rumor(14, alice, createdAt + DAY) + val statement = rumor(ConfederationKinds.PROPOSAL, alice, createdAt + DAY) + listOf(reply, statement).forEach { + db.groupInboxDao().insertMessage( + GroupInboxMessage(chatRoomId = group, rumorId = it.id, wrapId = null, conversationId = alice, participants = alice, + senderPublicKey = alice, kind = it.kind, rumorJson = it.toJson(), createdAt = createdAt, generation = 1, outgoing = false) + ) + } + + DisappearingMessageSweeper.sweep(db, ProtocolRetention, now = Instant.fromEpochSeconds(createdAt + DAY)) + + assertNull(db.groupInboxDao().getMessage(group, reply.id)) + assertNotNull(db.groupInboxDao().getMessage(group, statement.id), "a statement went with the conversation's messages") + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/DisappearingSweepJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/DisappearingSweepJvmTest.kt new file mode 100644 index 00000000..b7f821e6 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/DisappearingSweepJvmTest.kt @@ -0,0 +1,226 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync +import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler +import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent +import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlin.time.Instant +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.GiftWrapPayload +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.repository.DatabaseChatRepository +import mobi.giza.compose.database.repository.DisappearingSettingsStore +import mobi.giza.compose.nostr.DisappearingMessages +import mobi.giza.compose.nostr.DisappearingMessages.DAY +import mobi.giza.compose.nostr.DisappearingMessages.HOUR +import mobi.giza.compose.nostr.frost.FrostSigningEvents + +/** + * docs/disappearing-messages.md, Phase 4: what the sweeper deletes, what it must not, and what + * happens to a message that arrives already expired. + */ +class DisappearingSweepJvmTest { + + private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDb() = db.close() + + private val userKeys = KeyPair() + private val aliceKeys = KeyPair() + private val user = userKeys.pubKey.toHexKey() + private val alice = aliceKeys.pubKey.toHexKey() + private val relay = "wss://relay.example" + + private val repository = DatabaseChatRepository(database = db, scope = CoroutineScope(Dispatchers.Unconfined)) + private val store = DisappearingSettingsStore(db) + + private suspend fun seedProfile(publicKey: String) { + val nostrEventId = publicKey.take(63) + "f" + db.nostrEventDao().upsert(NostrEvent(id = nostrEventId, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = publicKey, userName = "member", nostrEventId = nostrEventId)) + } + + private suspend fun room(): LocalChatRoom { + seedProfile(user) + seedProfile(alice) + return assertNotNull(db.nostrNip17Dao().createNip17ChatRoom(user, listOf(alice))) + } + + /** Sends and seals one message under a one-hour policy; returns its payload. */ + private suspend fun sentMessage(room: LocalChatRoom): GiftWrapPayload { + store.saveDefault(user, HOUR) + repository.sendChatMessage(text = "gone in an hour", localChatRoom = room) + val payload = db.giftWrapPayloadDao().getByChatRoomAndKinds(room.chatRoom.id, listOf(14)).single() + repository.sealGiftWrapPayload(payload, NostrSignerSync(userKeys)) + return assertNotNull(db.giftWrapPayloadDao().getById(payload.id)) + } + + @Test + fun `nothing goes before its expiry`(): Unit = runBlocking { + val room = room() + val payload = sentMessage(room) + val swept = DisappearingMessageSweeper.sweep(db, WrittenOnlyRetention, now = assertNotNull(payload.expiresAt) - kotlin.time.Duration.parse("1s")) + assertEquals(0, swept.payloads) + assertNotNull(db.chatMessageDao().getChatMessagesByGiftWrapPayloadId(payload.id)) + } + + @Test + fun `an expired message goes with every wrap and seal that held it, and the room stays`(): Unit = runBlocking { + val room = room() + val payload = sentMessage(room) + val line = assertNotNull(db.chatMessageDao().getChatMessagesByGiftWrapPayloadId(payload.id)) + assertEquals(2, db.giftWrapSealDao().getAllGiftWrapSeals().size) + + val swept = DisappearingMessageSweeper.sweep(db, WrittenOnlyRetention, now = assertNotNull(payload.expiresAt)) + + assertEquals(1, swept.payloads) + assertEquals(setOf(line.id), swept.messageIds) + assertNull(db.giftWrapPayloadDao().getById(payload.id)) + assertNull(db.chatMessageDao().getChatMessagesByGiftWrapPayloadId(payload.id)) + assertEquals(emptyList(), db.giftWrapSealDao().getAllGiftWrapSeals(), "a seal the sender could still decrypt survived") + assertEquals(emptyList(), db.giftWrapMessageDao().getAllGiftWrapMessages(), "a wrap survived its message") + assertNotNull(db.chatRoomDao().findChatRoomById(room.chatRoom.id), "the conversation went with the message") + } + + @Test + fun `the payload a room was created from goes without taking the room`(): Unit = runBlocking { + val room = room() + val payload = sentMessage(room) + db.chatRoomDao().upsert(room.chatRoom.copy(initialGiftWrapPayloadId = payload.id)) + + DisappearingMessageSweeper.sweep(db, WrittenOnlyRetention, now = assertNotNull(payload.expiresAt)) + + val after = assertNotNull(db.chatRoomDao().findChatRoomById(room.chatRoom.id), "the room cascaded away with its first payload") + assertNull(after.chatRoom.initialGiftWrapPayloadId) + } + + @Test + fun `a ceremony's expired round stays until its session lets it go`(): Unit = runBlocking { + val room = room() + val createdAt = Clock.System.now().epochSeconds - 2 * DAY + val tags = store.stamp(room.chatRoom.id, user, FrostSigningEvents.NONCE, createdAt, arrayOf(arrayOf("p", alice))) + val round = GiftWrapPayload( + id = EventHasher.hashId(user, createdAt, FrostSigningEvents.NONCE, tags, "nonce"), + publicKey = user, chatRoomId = room.chatRoom.id, kind = FrostSigningEvents.NONCE, + tags = tags, content = "nonce", createdAt = Instant.fromEpochSeconds(createdAt), + ) + db.giftWrapPayloadDao().upsert(round) + + assertEquals(0, DisappearingMessageSweeper.sweep(db, WrittenOnlyRetention).payloads) + assertNotNull(db.giftWrapPayloadDao().getById(round.id), "a round was swept before its session finished") + + assertEquals(1, DisappearingMessageSweeper.sweep(db, { _, _ -> true }).payloads) + assertNull(db.giftWrapPayloadDao().getById(round.id)) + } + + @Test + fun `a message that expired before it was sent is swept and counted`(): Unit = runBlocking { + val room = room() + store.saveDefault(user, HOUR) + repository.sendChatMessage(text = "never sent", localChatRoom = room) + val payload = db.giftWrapPayloadDao().getByChatRoomAndKinds(room.chatRoom.id, listOf(14)).single() + + val swept = DisappearingMessageSweeper.sweep(db, WrittenOnlyRetention, now = assertNotNull(payload.expiresAt)) + assertEquals(1, swept.unsent) + assertNull(db.chatMessageDao().getChatMessagesByGiftWrapPayloadId(payload.id)) + } + + /** A wrap from alice to the user, carrying a kind 14 with [expiry]. */ + private fun wrapFromAlice(createdAt: Long, expiry: Long?): NostrEvent { + val tags = listOfNotNull(arrayOf("p", user), expiry?.let { arrayOf("expiration", it.toString()) }).toTypedArray() + val rumor = RumorAssembler.assembleRumor(alice, EventTemplate(createdAt, 14, tags, "dumela")) + val signer = NostrSignerSync(aliceKeys) + val seal = signer.signNormal( + createdAt = createdAt - 100, + kind = SealEvent.KIND, + tags = emptyArray(), + content = signer.nip44Encrypt(plaintext = rumor.toJson(), toPublicKey = user), + ) + val wrapCreatedAt = createdAt - 200 + val wrap = GiftWrapEvent.create( + event = seal, + recipientPubKey = user, + createdAt = wrapCreatedAt, + expirationDelta = expiry?.let { it - createdAt }, + ) + return NostrEvent( + id = wrap.id, pubKey = wrap.pubKey, kind = wrap.kind, tags = wrap.tags, + content = wrap.content, sig = wrap.sig, createdAt = Instant.fromEpochSeconds(wrap.createdAt), + ) + } + + private suspend fun receive(wrap: NostrEvent) = + db.nostrDao().storeNostrEvent(nostrEvent = wrap, relayURL = relay, synchronizationRelayURLs = listOf(relay), level = 0, activeKeyPair = userKeys) + + @Test + fun `a message received live carries its sender's expiry, and its wrap goes with it`(): Unit = runBlocking { + room() + val now = Clock.System.now().epochSeconds + val wrap = wrapFromAlice(now, now + HOUR) + receive(wrap) + + val payload = db.giftWrapPayloadDao().getByKinds(listOf(14)).single() + assertEquals(Instant.fromEpochSeconds(now + HOUR), payload.expiresAt) + val line = assertNotNull(db.chatMessageDao().getChatMessagesByGiftWrapPayloadId(payload.id)) + assertEquals(payload.expiresAt, line.expiresAt) + assertEquals(payload.id, db.giftWrapMessageDao().getAllGiftWrapMessages().single().giftWrapPayloadId) + + DisappearingMessageSweeper.sweep(db, WrittenOnlyRetention, now = Instant.fromEpochSeconds(now + HOUR)) + assertNull(db.nostrEventDao().getNostrEventById(wrap.id), "the wrap outlived the message it carried") + assertNull(db.chatMessageDao().getChatMessagesByGiftWrapPayloadId(payload.id)) + } + + @Test + fun `a message that arrives already expired is not filed, and its wrap is emptied and remembered`(): Unit = runBlocking { + room() + val now = Clock.System.now().epochSeconds + val wrap = wrapFromAlice(now - 2 * HOUR, now - HOUR) + receive(wrap) + + assertEquals(emptyList(), db.giftWrapPayloadDao().getByKinds(listOf(14)), "an expired message was filed") + assertEquals(emptyList(), db.giftWrapSealDao().getAllGiftWrapSeals(), "the seal this device can read was kept") + assertEquals("", assertNotNull(db.nostrEventDao().getNostrEventById(wrap.id)).content, "the ciphertext was kept") + assertTrue(db.disappearingDao().isTombstoned(wrap.id)) + + // Once the wrap's own expiry passes, the empty row goes too. + val wrapRow = db.giftWrapMessageDao().getAllGiftWrapMessages().single() + DisappearingMessageSweeper.sweep(db, WrittenOnlyRetention, now = assertNotNull(wrapRow.expiresAt)) + assertNull(db.nostrEventDao().getNostrEventById(wrap.id)) + + // A relay serving it again is turned away before anything is opened. + receive(wrap) + assertNull(db.nostrEventDao().getNostrEventById(wrap.id)) + assertEquals(emptyList(), db.giftWrapPayloadDao().getByKinds(listOf(14))) + } + + @Test + fun `another sender's expiry is obeyed whatever this device's own setting is`(): Unit = runBlocking { + room() + store.saveDefault(user, DisappearingMessages.OFF) + val now = Clock.System.now().epochSeconds + receive(wrapFromAlice(now, now + HOUR)) + val payload = db.giftWrapPayloadDao().getByKinds(listOf(14)).single() + + DisappearingMessageSweeper.sweep(db, WrittenOnlyRetention, now = Instant.fromEpochSeconds(now + HOUR)) + assertNull(db.giftWrapPayloadDao().getById(payload.id)) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ProtocolRetentionJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ProtocolRetentionJvmTest.kt new file mode 100644 index 00000000..5653766f --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ProtocolRetentionJvmTest.kt @@ -0,0 +1,142 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlin.time.Instant +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.database.model.GiftWrapPayload +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.model.types.DkgRitualStage +import mobi.giza.compose.database.model.types.FrostSigningStage +import mobi.giza.compose.database.repository.DisappearingSettingsStore +import mobi.giza.compose.nostr.DisappearingMessages +import mobi.giza.compose.nostr.DisappearingMessages.DAY +import mobi.giza.compose.nostr.dkg.DkgRitualEvents +import mobi.giza.compose.nostr.frost.FrostSigningEvents + +/** + * docs/disappearing-messages.md, Phase 5: a ceremony's rounds outlive their expiry exactly as long + * as the session they belong to is still open, and no longer. + */ +class ProtocolRetentionJvmTest { + + private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDb() = db.close() + + private val user = KeyPair().pubKey.toHexKey() + private val alice = KeyPair().pubKey.toHexKey() + private val dkgId = "d".repeat(64) + private val signingId = "5".repeat(64) + + private suspend fun seedProfile(publicKey: String) { + val nostrEventId = publicKey.take(63) + "f" + db.nostrEventDao().upsert(NostrEvent(id = nostrEventId, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = publicKey, userName = "member", nostrEventId = nostrEventId)) + } + + private suspend fun room(): LocalChatRoom { + seedProfile(user) + seedProfile(alice) + return assertNotNull(db.nostrNip17Dao().createNip17ChatRoom(user, listOf(alice))) + } + + private fun dkg(room: LocalChatRoom, stage: DkgRitualStage) = DkgSession( + id = dkgId, + chatRoomId = room.chatRoom.id, + coordinatorPublicKey = user, + userPublicKey = user, + threshold = 2, + participantCount = 2, + stage = stage, + hostPublicKey = user, + round1Random = "aa".repeat(32), + round2AuxRandom = "bb".repeat(32), + ) + + private fun signing(room: LocalChatRoom, stage: FrostSigningStage) = FrostSigningSession( + id = signingId, + chatRoomId = room.chatRoom.id, + coordinatorPublicKey = user, + userPublicKey = user, + dkgSessionId = dkgId, + threshold = 2, + participantCount = 2, + signerId = 0, + stage = stage, + ) + + /** A round queued two weeks ago, so it is past even the ceremony floor. */ + private suspend fun expiredRound(room: LocalChatRoom, kind: Int, sessionTags: Array>): GiftWrapPayload { + val createdAt = Clock.System.now().epochSeconds - 14 * DAY + val tags = DisappearingSettingsStore(db).stamp(room.chatRoom.id, user, kind, createdAt, arrayOf(arrayOf("p", alice)) + sessionTags) + val payload = GiftWrapPayload( + id = EventHasher.hashId(user, createdAt, kind, tags, "round"), + publicKey = user, chatRoomId = room.chatRoom.id, kind = kind, + tags = tags, content = "round", createdAt = Instant.fromEpochSeconds(createdAt), + ) + db.giftWrapPayloadDao().upsert(payload) + return payload + } + + @Test + fun `a key ceremony's round stays while the ceremony runs, and goes once it is complete`(): Unit = runBlocking { + val room = room() + db.dkgSessionDao().upsert(dkg(room, DkgRitualStage.COLLECTING_ROUND_1)) + val round = expiredRound(room, DkgRitualEvents.ROUND_1, DkgRitualEvents.assembleTags(sessionId = dkgId)) + + assertFalse(ProtocolRetention.isReleased(db, round)) + assertEquals(0, DisappearingMessageSweeper.sweep(db, ProtocolRetention).payloads) + assertNotNull(db.giftWrapPayloadDao().getById(round.id)) + + db.dkgSessionDao().upsert(dkg(room, DkgRitualStage.COMPLETE)) + assertEquals(1, DisappearingMessageSweeper.sweep(db, ProtocolRetention).payloads) + assertNull(db.giftWrapPayloadDao().getById(round.id)) + assertEquals(DkgRitualStage.COMPLETE, assertNotNull(db.dkgSessionDao().getSessionById(dkgId)).stage, "the ceremony's result went with its rounds") + } + + @Test + fun `a signing round stays while signing runs, and goes once it has failed`(): Unit = runBlocking { + val room = room() + db.dkgSessionDao().upsert(dkg(room, DkgRitualStage.COMPLETE)) + db.frostSigningSessionDao().upsert(signing(room, FrostSigningStage.COLLECTING_NONCES)) + val nonce = expiredRound(room, FrostSigningEvents.NONCE, FrostSigningEvents.assembleTags(sessionId = signingId)) + + assertFalse(ProtocolRetention.isReleased(db, nonce)) + db.frostSigningSessionDao().upsert(signing(room, FrostSigningStage.FAILED)) + assertTrue(ProtocolRetention.isReleased(db, nonce)) + } + + @Test + fun `a round no session here will read is released at its expiry`(): Unit = runBlocking { + val room = room() + val stray = expiredRound(room, FrostSigningEvents.NONCE, FrostSigningEvents.assembleTags(sessionId = signingId)) + assertTrue(ProtocolRetention.isReleased(db, stray)) + } + + @Test + fun `a Welcome and what a person wrote are released at their expiry`(): Unit = runBlocking { + val room = room() + assertTrue(ProtocolRetention.isReleased(db, expiredRound(room, WelcomeEvent.KIND, emptyArray()))) + assertTrue(ProtocolRetention.isReleased(db, expiredRound(room, 14, emptyArray()))) + assertEquals(DisappearingMessages.ExpiryClass.Written, DisappearingMessages.classOf(14)) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationPolicyJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationPolicyJvmTest.kt index 030001ef..341f8b80 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationPolicyJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationPolicyJvmTest.kt @@ -114,4 +114,11 @@ class NotificationPolicyJvmTest { assertEquals(Drop(Reason.TooOld), decide(line(at = now - NotificationPolicy.HORIZON - 1.hours))) assertEquals(Post(NotificationCategory.Messages), decide(line(at = now - NotificationPolicy.HORIZON + 1.hours))) } + + /** docs/disappearing-messages.md, D6: a notification would be a disappeared message's last copy. */ + @Test + fun `a line past its expiry has disappeared, and is not posted`() { + assertEquals(Drop(Reason.Expired), decide(line().copy(expiresAt = now))) + assertEquals(Post(NotificationCategory.Messages), decide(line().copy(expiresAt = now + 1.hours))) + } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/DisappearingLengthJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/DisappearingLengthJvmTest.kt new file mode 100644 index 00000000..9b431e82 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/DisappearingLengthJvmTest.kt @@ -0,0 +1,39 @@ +package mobi.giza.compose.ui.composable + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import mobi.giza.compose.nostr.DisappearingMessages +import mobi.giza.compose.ui.composable.DisappearingLength.Unit.DAYS +import mobi.giza.compose.ui.composable.DisappearingLength.Unit.HOURS +import mobi.giza.compose.ui.composable.DisappearingLength.Unit.MINUTES +import mobi.giza.compose.ui.composable.DisappearingLength.Unit.WEEKS + +/** docs/disappearing-messages.md, Phase 6: how a length reads, and what the custom dialog accepts (D3). */ +class DisappearingLengthJvmTest { + + @Test + fun `a length reads in the largest unit it is a whole number of`() { + assertNull(DisappearingLength.split(DisappearingMessages.OFF)) + assertEquals(HOURS to 1L, DisappearingLength.split(DisappearingMessages.HOUR)) + assertEquals(HOURS to 8L, DisappearingLength.split(8 * DisappearingMessages.HOUR)) + assertEquals(DAYS to 1L, DisappearingLength.split(DisappearingMessages.DAY)) + assertEquals(WEEKS to 1L, DisappearingLength.split(7 * DisappearingMessages.DAY)) + assertEquals(WEEKS to 4L, DisappearingLength.split(28 * DisappearingMessages.DAY)) + assertEquals(MINUTES to 90L, DisappearingLength.split(90 * DisappearingMessages.MINUTE)) + assertEquals(DAYS to 365L, DisappearingLength.split(DisappearingMessages.MAX_SECONDS)) + } + + @Test + fun `the custom dialog takes whole numbers within five minutes and a year`() { + assertEquals(5 * DisappearingMessages.MINUTE, DisappearingLength.parse("5", MINUTES)) + assertEquals(36 * DisappearingMessages.HOUR, DisappearingLength.parse(" 36 ", HOURS)) + assertEquals(DisappearingMessages.MAX_SECONDS, DisappearingLength.parse("365", DAYS)) + assertNull(DisappearingLength.parse("4", MINUTES)) + assertNull(DisappearingLength.parse("366", DAYS)) + assertNull(DisappearingLength.parse("0", HOURS)) + assertNull(DisappearingLength.parse("", HOURS)) + assertNull(DisappearingLength.parse("1.5", HOURS)) + assertNull(DisappearingLength.parse("99999999999999", DAYS)) + } +} diff --git a/docs/README.md b/docs/README.md index 9a3933e2..219d04a8 100644 --- a/docs/README.md +++ b/docs/README.md @@ -31,6 +31,7 @@ the [retired](./retired/) notes now. | [mls-skipped-keys.md](./mls-skipped-keys.md) | why a group event that arrives a moment late was dropped for good, which flows triggered it, the fix as it landed in mls-kmp, and the one word of the diagnosis that was wrong | | [long-running-sync.md](./long-running-sync.md) | the chat subscriptions that stay open instead of pulling once per screen — why the request queue could not simply hold one, and how the group filter follows the room list | | [notifications-and-background-sync.md](./notifications-and-background-sync.md) | notifications, and the background sync they need: a phased plan, built on Android and desktop but for its device run, written but not compiled on iOS, with the background half behind a flag that is off in release. Read state per room, then notifications for as long as the process lives, then a bounded background pass on WorkManager, BGTaskScheduler and the desktop tray. Covers why notifications come from the table rather than the wire, why the cursor is a row id and never a timestamp, why the object graph has to leave the composition first, what each platform can honestly offer, and real-time push (MIP-05) as the owner's decision rather than a phase | +| [disappearing-messages.md](./disappearing-messages.md) | every NIP-17 message Giza sends expires, a day by default: a phased plan, built but for its device run and not behind a flag. What a person writes follows their policy, which they can change for everything or one conversation; a ceremony's rounds always expire, after a floor their protocol can live with, and leave the device only once their session is done. Covers why the seal stays untagged though quartz tags it, why the wrap's expiry is pushed later at random, how a payload's wraps and seals are deleted with it and never before it, the room a cascade would have taken with its first message, and what a group signs when it sends | | [dead-code.md](./dead-code.md) | code in the sync and relay stack that nothing calls, why each piece is still there, and which of it is a bug rather than a leftover | | [nsec-sign-in.md](./nsec-sign-in.md) | signing in with an existing nostr key — why an nsec can never have a wallet behind it, the ten call sites that make it small, and the sign-in machine that was already built and unreachable | | [npub-sign-in.md](./npub-sign-in.md) | signing in with only a public key — what a key that cannot sign can still see here, why that is a preview rather than a browser, and the four decisions the word settles | diff --git a/docs/disappearing-messages.md b/docs/disappearing-messages.md new file mode 100644 index 00000000..1af75bca --- /dev/null +++ b/docs/disappearing-messages.md @@ -0,0 +1,788 @@ +# Disappearing NIP-17 messages, one day by default + +A plan to give every NIP-17 event Giza sends a NIP-40 `expiration`, with no exceptions. That +includes what a person writes, what a group sends, and every ceremony round, signing round, +confederation statement and Welcome that travels the same way. What a person writes expires one +day after it is written unless they choose otherwise. When that time comes, both people's Giza +deletes it, and the relays holding the wrap are asked to drop it. Protocol messages expire too, +on a clock that is never shorter than the protocol needs (D2). A person can change the length +for what they write, or turn it off. They can do this for everything they send, or for one +conversation. + +Written against `3b0b3c9a` on 2026-11-22. **Built, Phases 0 to 7**, on +`claude/disappearing-messages`, one commit per phase. The device run (Phase 8) has not been done. +It is **not behind a flag**: a build with this in it stamps a one-day expiry on what everyone +writes in NIP-17 from the first message after the upgrade. Revised the same day as it was written: +protocol messages were first left out, and now expire too. Each phase says what was built and +where it differs from the plan. + +Read [marmot-direct-messages.md](./marmot-direct-messages.md) before changing anything on the +send path. It explains why a `GiftWrapPayload` row with a null seal id leaves the device, and +that rule is the one this plan touches most. [frost-session-resend.md](./frost-session-resend.md) +already treats a NIP-40 expiry as one of the reasons a member can miss a round, and that is +why signing rounds can expire with the person's own setting. [group-threshold-ecdh.md](./group-threshold-ecdh.md) +and [group-inbox.md](./group-inbox.md) cover the two ways a *group* sends NIP-17. + +## What the NIPs say, and where they disagree + +- **NIP-17**: clients "MAY offer disappearing messages by setting an `expiration` tag in the gift + wrap of each receiver". The tag "SHOULD be included on the `kind:13` seal as well, in case it + leaks". NIP-17 says nothing about the rumor (kind 14), and it defines no event for a shared + or preferred expiry. Each sender decides for their own messages. +- **NIP-59**: "Tags MUST always be empty in a `kind:13`." This conflicts directly with NIP-17's + seal advice. NIP-59 also says that when both layers carry expirations, each layer should use + its own random timestamp. +- **NIP-40**: the expiration is an absolute unix time. Relays "SHOULD drop" events that are + already expired when published, and "SHOULD NOT send expired events to clients", but they + "MAY persist them indefinitely". Clients "SHOULD ignore events that have expired" and "SHOULD + NOT send expiration events to relays that do not support this NIP". NIP-40 also says plainly + that expiration is **not a security feature**. + +The plan follows from these. The rumor's expiration is what Giza obeys, because it is the only +copy the sender signed (through the seal) and the only one the recipient can trust. The wrap's +expiration is a request to relays. The seal stays empty (D5). + +## Where NIP-17 leaves Giza today + +Every outbound gift wrap comes from one of these sources, and none of them sets an expiration +today. Under this plan, all of them do. + +| Path | Builds the wrap | What it carries | Clock (D2) | +|---|---|---|---| +| A person writing in a NIP-17 room | `DatabaseChatRepository.sendChatMessage` → `GiftWrapPayload` → `sealGiftWrapPayload` → `NostrNip17Dao.persistAndBroadcastGiftWrap` | kind 14 and the other kinds a person writes | the person's policy | +| The notification quick reply | `NotificationActions` → `sendChatMessage` | kind 14 | the person's policy | +| A group writing to someone | `GroupDmSender.wrapOwed` (`GiftWrapEvent.create`) | a rumor signed by the group, sealed by threshold ECDH | the person's policy, signed by the quorum | +| A group's inbox reply | `InboxReplies.wrapAndOwe` (`InboxWrap.wrap`) | a rumor signed by the group, sealed to the NIP-4E key | the person's policy, signed by the quorum | +| Key ceremony rounds | `GiftWrapPayload` rows from `ChillDkgRitualManager` | DKG rounds | protocol floor | +| Signing rounds | `GiftWrapPayload` rows from `FrostSigningManager` | FROST proposal, nonce, signer set, partials, signature, failure, decline | protocol floor | +| Confederation statements | `GiftWrapPayload` rows from `ConfederationRitualManager` | statements, which already carry an `expiration` of their own | the proposal's own expiry | +| The Marmot Welcome | `MarmotOutboundDao.deliveryWelcome` → `GiftWrapPayload` | kind 444 | protocol floor | + +Three other facts matter here: + +- `sealGiftWrapPayload` seals a copy to **every** participant, including the sender, so a second + device of the sender's can read their own messages. NIP-17 suggests leaving out the sender's + copy as one way to make messages disappear. This plan keeps the copy (D5). +- **Ceremonies read their own rounds back out of the payload table.** In a NIP-17 room, + `ChillDkgRitualManager` (around line 610), `ConfederationRitualManager` (around line 603) and + `FrostSigningManager` (around line 869) rebuild a session from the `GiftWrapPayload` rows + stored for it. `FrostSigningManager.isQueued` (around line 3241) uses the same table to avoid + queueing a round twice. Deleting a protocol payload is therefore not like deleting a chat + line. It is what D6 and Phase 5 deal with. +- The only NIP-17 relay is `Relays.DefaultDMRelayList = [wss://ephemeral.mantra.press]`. Sending + to the recipient's kind 10050 relays is written in `persistAndBroadcastGiftWrap` but commented + out. Whether the relay drops anything depends on that one relay (D8). + +Marmot (MLS) rooms are not NIP-17 and are out of scope. Their messages travel as kind 445, which +already carries the group's own retention (`MlsGroup.retentionSeconds`, +`MarmotInnerEvent.disappearingExpiration`). The retention applies to *every* inner kind there, +ceremony rounds included. That is the precedent this plan follows for NIP-17 rooms. A Marmot +direct message is a NIP-59 wrap that never reaches a relay. See D11. + +## Decisions + +### D1. The sender decides, and the setting is about the messages *you* send + +NIP-17 has no shared conversation timer. Each message carries its sender's choice, so the setting +is worded as **"Messages you send disappear after…"** everywhere. It is never worded as "this +chat disappears". Two Giza users who both keep the default will see the whole conversation +disappear after a day. A peer who chooses a week makes their own messages last a week. A peer on +a client without expirations sends messages that never expire, and Giza does not invent an +expiry for them. + +A local "also delete what I receive after…" retention is a separate feature. It is listed under +[Out of scope](#out-of-scope) so it does not get mixed in here. + +### D2. Everything expires, on one of two clocks + +Every event that goes into a NIP-17 wrap gets an expiration. There is no allowlist and no +exception. What differs is how long it lives: + +- **What a person writes** (kinds 14, 15, 7, and 5 when it deletes one of these) expires after the + person's policy (D3, D4). The policy can be Off, and Off means these messages carry no + expiration. +- **Protocol messages** expire after `max(policy, floor)`, where each protocol has its own floor. + They **always** expire. Off turns off expiry for what a person writes, not for ceremonies. A + ceremony round that lived forever on a relay would be the one exception to "everything + expires", and the point of this revision is that there are none. + +The floors start from each protocol's own timeline. Phase 0 checks them against the code: + +| Protocol | Kinds | Floor | Why | +|---|---|---|---| +| FROST signing | 30320–30325, 30330 | 1 day | `frost-session-resend.md` already handles a round that expired off a relay. The proposer resends, and a fresh event carries a fresh expiry. The floor only stops a 1-hour setting from making every signing a race | +| Key ceremonies (DKG, inbox key, share refresh) | each ritual's `ALL` set | 7 days | A ceremony waits for every admin, and an admin can be away for days. There is no resend for a DKG round | +| Confederation statements | the confederation statement kinds | the proposal's `expiresAt` (at most 30 days, `ConfederationKinds.MAX_EXPIRY_SECONDS`) | The rumor already carries `["expiration", expiresAt]`, meaning the proposal lapses then. That tag is already NIP-40-shaped, so it *is* the rumor's expiration. Giza does not add a second one (D5) | +| Marmot Welcome | 444 | 7 days | The invitee holds no group state yet and may not open the app for days | +| Anything not listed | any other kind | 7 days | A new kind still expires, and a test fails until someone classifies it on purpose (Phase 1) | + +`DisappearingMessages.classOf(kind)` returns `Written` or `Protocol(floor)`. Classifying a new +kind is a one-line change with a reason. Forgetting to classify it gives it the safe default of +seven days, not "never". + +**Expiring on the relay is not the same as deleting on the device.** A protocol payload's rows +stay on the device until its session has finished *and* its expiry has passed (D6). The keys, +shares, signatures and session records a ceremony produces are not messages. They do not expire, +because they are the result the ceremony existed to produce. + +### D3. One day by default, presets, and a bounded custom length + +The presets are **Off, 1 hour, 8 hours, 1 day (default), 1 week, 4 weeks**, plus **Custom**, +which takes a number and a unit (minutes, hours, days). Custom allows **5 minutes to 365 days**. + +- The 5-minute floor covers clock skew between two phones and the time it takes a message to be + delivered while the notary is catching up. Below that, a message can arrive already expired + and be dropped (D6). +- The 365-day ceiling keeps the value inside a range that relays and other clients handle without + surprises, and still lets "a long time" be a real choice. + +Values are stored as seconds. `0` means Off and `null` means "follow the default" (D4). + +### D4. A default for the identity, and an override per conversation + +- **The identity's default** lives in the aux database, keyed by `userPublicKey`. This is the same + place and shape as `NotificationLedger`, which `NotificationSettingsStore` already reads and + writes. A new identity starts at 86 400 seconds. So does an existing identity when the + migration runs (D9). +- **A conversation's override** is a nullable `ChatRoom.disappearingMessageSecs`. `null` follows + the default, `0` is Off for this conversation only, and any other value is that many seconds. + Only NIP-17 rooms show the override (`mlsGroupState == null`). A quorum's or confederation's + NIP-17 room has an override like any other room, and its protocol messages read their policy + from it. + +The expiry for a message is worked out once, when it is queued: +`DisappearingMessages.expiryFor(kind, createdAt, policy = room.disappearingMessageSecs ?: identityDefault)`. +The result is written into the payload's tags. Changing the setting later never changes a message +that has already been sent. It cannot, because the tag is part of the rumor's id. + +### D5. Which layers get a timestamp, and which timestamp + +- **Rumor**: `["expiration", expiry]`, worked out from the rumor's real `created_at` (D2). Giza + obeys this value, on both sides. A rumor that already carries an `expiration` keeps it and gets + no second one. Today that is only a confederation statement. A second tag would get the + statement refused: `ConfederationStatements` reads its tags with `singleOrNull`, and two + `expiration` tags read as none. +- **Wrap**: `["expiration", wrap.created_at + (rumorExpiration - rumor.created_at) + 2 days]`. + This is quartz's own formula (`GiftWrapEvent.build`'s `expirationDelta`). The wrap's + `created_at` is already pushed up to two days into the past so that a relay cannot see when a + message was really sent, and the formula carries that same random offset into the expiry. The + result is the rumor's expiry plus a random `[0, 2 days]`. A wrap expiry of exactly + `created_at + 86400` would give the send time away again. The offset only ever moves the expiry + *later*, so a relay never drops a wrap before the sender meant it to. The cost is that the + ciphertext can sit on the relay for up to two extra days. When the rumor has no expiration (a + person's message with the policy Off), the wrap has none either. +- **Seal**: no tag. Phase 0 found that quartz does tag the seal. Giza still does not, for three + reasons. NIP-59 says seal tags MUST be empty. Giza's own `GroupDmRefusal` refuses a group's seal + with any tag, and `InboxRefusal` refuses an inbox seal with more than one. And quartz's + `Rumor.mergeWith`, which Giza's receive path uses, appends the seal's tags to the rumor's. So a + tagged seal would put a second `expiration` on every rumor Giza receives. +- **The sender's own copy** is kept and given the same rumor expiry. A second device of the + sender's can then read the sender's half of the conversation for as long as the recipient can. + It also lets that device join a ceremony that a first device started. NIP-17's other option, + sending no self-copy, would silently break both. + +The randomness comes from the wrap's own `created_at`, so tests control it by passing that value +in. + +### D6. Deleting locally is the feature, and protocol payloads wait for their session + +The relay part is best effort. What a person actually experiences is their own device deleting +the message, so: + +- **What a person wrote is deleted at the rumor's expiration, on both sides.** The deletion is a + hard delete of the `ChatMessage` row and everything that holds its words: the + `GiftWrapPayload`, the `GiftWrapSeal`, the wrap's `NostrEvent` and `GiftWrapMessage`, the + broadcast-request relation rows, and any notification-ledger entry that stores message text. A + soft delete would leave the words on disk, which defeats the point. +- **A protocol payload is deleted at the later of its expiration and its release.** "Released" + means the session it belongs to has finished: completed, failed or abandoned. A + `PayloadRetention` hook per protocol answers that question (Phase 5). Until then the rows stay, + because the manager rebuilds the session from them. When the payload goes, any chat line it + rendered ("Alice proposed signing…") goes with it. The session's own record, and whatever the + session produced, stays. +- **A message that has already expired when it arrives is not filed and does not notify.** This + is NIP-40's "ignore expired events". It can happen because the wrap outlives the rumor on the + relay (D5), and because re-syncs happen. An expired protocol round that arrives late is ignored + the same way. Its session either had what it needed already, or a resend brings a fresh copy. +- **A wrap that has been deleted is not decrypted again.** A small + `ExpiredGiftWrap(id, dropAfter)` tombstone remembers wraps that were already handled until the + wrap's own expiration has passed. Without it, every sync would download the jittered wrap + again, decrypt it, find it expired, and throw it away. The outbound side needs no tombstone. + `FrostSigningManager.isQueued` only stops a re-published round from overwriting a row that is + still stored, and once a swept row has gone there is nothing for it to overwrite. +- **Expirations from other people are obeyed whatever this device's own setting is.** A message + that a Bennu user sent with a one-hour expiry disappears after an hour. +- **A reply that quotes a deleted message** shows "This message has disappeared" in place of the + quote. It never shows the quoted text, which would be a second copy. +- **An OS notification** showing a message's text is cancelled when that message is deleted. + +### D7. Honest about what it is + +The settings screen and the conversation say what the feature does, and nothing more: + +> Messages you send are deleted from your devices and from the recipient's Giza after this time, +> and relays are asked to delete them too. Other apps, screenshots and relays that ignore the +> request can keep a copy. + +And, under the list of lengths: + +> Signing and key-ceremony messages always expire. They are kept for at least a day, or a week +> for key ceremonies, and are not deleted from this device until the ceremony they belong to has +> finished. + +The description also says what happens if the recipient is offline for longer than the chosen +time: the relay may drop the message before the recipient ever downloads it. That consequence is +real, and the default makes it more likely, so people should be told about it. + +### D8. The relay has to support NIP-40, and Phase 0 checks that it does + +NIP-40 says clients "SHOULD NOT send expiration events to relays that do not support this NIP". +Giza sends every NIP-17 wrap to `ephemeral.mantra.press`. Phase 0 reads that relay's NIP-11 +document. If `supported_nips` includes 40, nothing more is needed. If it does not, the fix is to +add support on the relay, or to add a second DM relay that supports it. The fix is **not** to +leave the tag off: the local deletion still works without relay support, and it is the larger +part of the feature. Turning sending to the recipient's 10050 relays back on is outside this +plan's scope. Phase 0 records the finding so that whoever re-enables it filters by +`supported_nips`. + +### D9. Existing users get the default from the next message they send + +The migration gives every existing identity the one-day default. Messages and rounds sent before +the upgrade stay as they were: the policy applies to what is sent after it and is never applied +retroactively. A ceremony that is open during the upgrade keeps running. Its earlier rounds have +no expiry, its later ones do, and the session does not care which is which. The first time a +person opens a NIP-17 conversation after the upgrade, a one-time notice says *"New messages you +send here disappear after 1 day"*, with an action that opens the setting. Without that notice, a +person's own words would start disappearing when they had changed nothing. + +### D10. When a group sends, the expiry is part of what its quorum signs + +For the two group paths, the rumor goes inside a seal that the group signs in a FROST round. That +puts the rumor's expiration inside what the admins sign: + +- The proposer's device sets the rumor expiration when it proposes, from the room's override or + the proposer's default. The signing review screen shows it, for example "Disappears 1 day after + it is sent", so every signer approves the expiry along with the words. +- A signer's device checks that the expiration is within D3's bounds. If it is not, the device + refuses the proposal out loud. It does not sign a message that would expire unreasonably early + or late. A message the group sends with no expiration is also refused, unless the proposer's + policy is Off. +- The device that wraps the message adds the wrap expiration with jitter (D5), as on the + one-to-one path. +- Both paths stay behind their existing flags (`groupDirectMessages`, `groupInbox`). + +### D11. MLS rooms are not covered, and the screen says so + +A group's Marmot room already has a group-wide retention that every member's client applies. +That is a different model: one value the group agrees on, set through a commit. The settings +screen states that the setting covers direct messages and quorum and confederation +conversations, and that a group's own room follows the group's setting. Letting a person set the +group's retention from Giza is a natural next step. It is a separate plan, because it is an MLS +proposal, not a tag. + +### D12. You can see a message is going to disappear + +- The app bar of a NIP-17 conversation shows an hourglass and the current length ("1 day") when + a policy is in force. Tapping it opens the conversation's setting. +- An expiring message has a small hourglass next to its time. Its `contentDescription` gives the + time left, because the icon carries information the text beside it does not. +- When an incoming message's expiry differs from the conversation's setting (D1), nothing extra + is shown. The hourglass already says that the message will go. +- Protocol lines get no hourglass. They always expire, so a marker on every one would carry no + information. + +## Phases + +### Phase 0: this document, and nine checks + +1. **quartz.** Does quartz's NIP-17 builder (`NIP17Factory` or its successor) put `expiration` on + the seal, the wrap, or both? Does `SealEvent` reject a seal with tags? This decides the seal + question in D5. +2. **The relay.** Fetch `ephemeral.mantra.press`'s NIP-11 document and look for 40 in + `supported_nips`. Also publish an already-expired test event and confirm the relay refuses it + (D8). +3. **Bennu.** Check that a Bennu build accepts an `expiration` tag on a kind 14 rumor **and on + every protocol rumor**. A Bennu device that refuses a DKG round it does not recognise would + stall every mixed Giza–Bennu ceremony. This needs a test, not an assumption. +4. **The kinds.** List every `kind` written to `GiftWrapPayload` today, from the code and from a + real database. Each one gets a class in D2's table. +5. **The floors.** For each protocol in D2's table, find how long a real session stays open: from + the code's timeouts and from the device runs in the protocol's own document. Raise a floor + that is too short. +6. **Readers of the payload table.** Confirm that `ChillDkgRitualManager`, + `ConfederationRitualManager` and `FrostSigningManager` are the only code that reads protocol + payloads back from `GiftWrapPayload`. For each one, find the session state that says + "finished". For confederation statements, find out whether the confederation's status is + *derived from the statements each time it is read*. If it is, deleting them erases a formed + confederation, and Phase 5 has to store the status first. +7. **Where words are stored.** Check the notification ledger, any search or full-text index, + draft storage, reply previews and the logs (`sealGiftWrapPayload` logs the rumor JSON at debug + level). Each place found gets a deletion step in Phase 4, or the log line is removed. +8. **Participants.** Confirm that every NIP-17 room includes the local user as a participant, so + that the sender's copy really is sealed (D5). +9. **The Welcome.** Read MIP-02 for anything it says about a Welcome's lifetime or expiration, and + adjust its floor to match. + +Done when: each check's answer is written under this phase, and D2, D5 and D8 are updated if an +answer changes them. + +**Done, 2026-11-22.** The checks were run against quartz 2.20.1 and marmot-kmp 2.3.0 from the +Magpie mirror, against the relay itself, and against Bennu's `bennu-kmp` at `2db6dde5`. + +1. **quartz** tags all three layers. The rumor carries the expiry. `SealEvent.build` and + `GiftWrapEvent.build` each add `created_at + delta + 2 days`, where `delta` is the rumor's + expiry minus its `created_at`. `SealEvent` does not refuse a tagged seal. `Rumor.mergeWith` + appends the seal's tags to the rumor's when it unseals, and `GiftWrapSeal.decryptGiftWrapPayload` + unseals that way. D5 now uses quartz's wrap formula and keeps the seal empty, for the reasons + given there. +2. **The relay.** `ephemeral.mantra.press` lists 40 in `supported_nips`, so D8 needs nothing + more. It also describes itself as `nak serve`, "a local relay for testing, debugging and + development". Phase 8's relay check should keep that in mind. +3. **Bennu** reads rumor tags by name. It has no check on the number of tags, or on unknown tags, + anywhere in `composeApp`. An extra `expiration` on the rumor is safe there. Bennu has no group + DM or inbox refusals, so the seal question does not reach it. +4. **The kinds.** Five producers write `GiftWrapPayload`: `sendChatMessage` (14, plus whatever + `messageType` a caller passes), `ChillDkgRitualManager` (its ritual kinds), + `FrostSigningManager` (the signing kinds, and any kind its queue is handed), + `ConfederationRitualManager` (the confederation DKG kinds) and `MarmotOutboundDao.deliveryWelcome` + (444). Every one of them hashes the rumor id from its tags itself, so each one has to stamp + before it hashes (Phase 3). +5. **The floors.** No ceremony has a timeout in code. A DKG, signing or confederation ceremony stays + open until it completes, fails or is abandoned. The floors in D2 stand. +6. **Readers of the payload table.** `ChillDkgRitualManager` (around line 610), + `ConfederationRitualManager` (around line 603) and `FrostSigningManager` (around line 869) are + the only readers. `ShareRefreshManager`, `InboxKeyRitualManager`, `ConfederationSigningManager` + and `ChronicleManager` read `MarmotInnerEvent` only, which is out of scope. Confederation + *statements* do not travel on this path at all. They go through the group inbox + (`GroupInboxManager`, `InboxReplies`), so the question of the confederation's stored status + moves to Phase 7. +7. **Where words are stored.** `NotificationLedger` stores a cursor and switches, but no text. + There is no full-text index and no draft table. `ChatMessage` has foreign keys to + `GiftWrapPayload` with `ON DELETE CASCADE`, so deleting a payload deletes its chat line. The + debug log of the rumor JSON in `sealGiftWrapPayload` is real, and Phase 3 removes it. +8. **Participants.** `createNip17ChatRoom` puts the local user in the room, and + `persistInboundChatMessage` already discards "our own message coming back". The self-copy is + sealed. +9. **The Welcome.** marmot-kmp's own `WelcomeGiftWrap` sets no expiration, and its sources say + nothing about a Welcome's lifetime. The seven-day floor stands. + +### Phase 1: pin today's behaviour, and the pure core + +- Tests that pin today: a payload sealed by `sealGiftWrapPayload` has no `expiration` on any + layer, and a confederation statement's existing `expiration` tag comes through unchanged. +- New `nostr/DisappearingMessages.kt`, pure functions only, with no database (the same pattern as + `MarmotDirectMessage`): + - `MIN_SECONDS`, `MAX_SECONDS`, `DEFAULT_SECONDS = 86_400`, `PRESETS` + - `classOf(kind): ExpiryClass`, which is `Written` or `Protocol(floorSeconds)`, with + `UNCLASSIFIED_FLOOR = 7 days` + - `policyFor(roomOverride: Long?, identityDefault: Long): Long?` + - `expiryFor(kind, createdAt, policy, existingTags): Long?`. It is null only for a `Written` + kind with the policy Off, and it returns the existing tag's value when there is one (D5). + - `wrapExpiration(rumorExpiration, rumorCreatedAt, wrapCreatedAt): Long` + - `expirationOf(tags): Long?` +- `commonTest`: + - **Every kind the app writes to the queue is classified explicitly.** The test lists the + ritual `ALL` sets, the FROST kinds, the confederation kinds and 444, and fails on any kind + that falls through to `UNCLASSIFIED_FLOOR`. This replaces the allowlist test from the first + draft. + - Protocol kinds expire even with the policy Off, at their floor. + - The bounds, Off versus `null`, the jitter staying within `[0, 2 days]` and never moving + earlier, and a malformed tag (non-numeric, or before `created_at`) parsing as "no + expiration". + +### Phase 2: storage + +Migration 49 → 50, following the pattern in `database/migrations/`: + +- `ChatRoom.disappearingMessageSecs: Long?` +- `ChatMessage.expiresAt: Instant?`, with an index so the sweeper's "next to expire" query is + cheap +- `GiftWrapPayload.expiresAt: Instant?`, so the sweeper can find protocol payloads without parsing + tags +- New table `ExpiredGiftWrap(id PRIMARY KEY, dropAfter)`, for wrap ids inbound and payload ids + outbound (D6) +- In the aux database: the identity default, stored next to (or as a column of) + `NotificationLedger`, with existing rows set to 86 400 (D9). A `DisappearingSettingsStore` has + the same shape as `NotificationSettingsStore`. +- `ChatRoom.disappearingNoticeShownAt: Instant?` for D9's one-time notice + +Tests: a migration JVM test in the style of `ReadMarkMigrationJvmTest`, run against a version-49 +database with NIP-17 and MLS rooms in it. + +**Built.** `AutoMigration(from = 49, to = 50)`, with no spec, because nothing moves. It differs from +the plan in two ways: + +- The identity's default is a table of its own, `DisappearingSetting(userPublicKey, defaultSeconds)`, + not a column of `NotificationLedger`. A ledger row exists only once notifications are armed, and + a policy has to apply before that. A missing row reads as one day, so D9's upgrade needs no data + step. +- `ExpiredGiftWrap` holds inbound wrap ids only (D6 dropped the outbound tombstone). +- `GiftWrapMessage` gains `giftWrapPayloadId` and `expiresAt`, which the plan did not have. The + cascade runs wrap → seal → payload → chat line, so deleting a wrap early would delete an + unfinished ceremony's round with it. The sender's one-per-recipient wraps also had no link to + their payload at all, only the first seal did. The sweeper needs both columns (Phase 4). +- `GiftWrapPayload.expiresAt` defaults to the value read off the row's own tags. Every producer + and the inbound path therefore record it without being changed. + +`DisappearingDao` and `DisappearingSettingsStore` sit beside them. `DisappearingMessagesMigrationJvmTest` +covers the upgrade, the store and the tombstones, and `ShippedProfileUpgradeJvmTest` now expects +version 50. + +**Found while building, and Phase 4 has to handle it:** `ChatRoom.initialGiftWrapPayloadId` is a +foreign key to `GiftWrapPayload` with `ON DELETE CASCADE`. `NostrDao` sets it to the payload that +first created a NIP-17 room on this device. Deleting that payload would delete the whole +conversation. The sweeper clears the reference before it deletes the payload. + +### Phase 3: sending, for every kind + +- **One place applies the policy.** A single `DisappearingMessages.stamp(payload, room, + identityDefault)` runs before *every* `GiftWrapPayload` is written. It appends the rumor + expiration to the tags, **before** the payload id is hashed, so the payload id is the id of the + rumor the recipient will see. It also sets `GiftWrapPayload.expiresAt`. The callers are + `sendChatMessage`, `ChillDkgRitualManager`, `FrostSigningManager`, + `ConfederationRitualManager` and `MarmotOutboundDao.deliveryWelcome`. Each of them hashes its + own id today, so each one moves to calling `stamp` first. A JVM test inserts a payload through + each caller and asserts that it has an expiration. That test is what stops a sixth caller from + skipping it. +- `sendChatMessage` also writes `ChatMessage.expiresAt`. +- `sealGiftWrapPayload` reads `expirationOf(giftWrapPayload.tags)`. When it finds one, it adds the + jittered expiration to the wrap's tags. The seal is left alone (D5, after Phase 0). The rumor + needs no change, because `RumorAssembler` already copies the payload's tags. +- `persistAndBroadcastGiftWrap` sets `NostrEvent.expiresAt` from the wrap. The existing + `NostrEventDao` predicate (`expiresAt IS NULL OR expiresAt > :now`) then covers it with no + further change. +- **A message whose rumor expired before it was sent** (the device was offline for longer than + the policy) is not sealed and not broadcast. For a person's message, the sweeper deletes its + chat message like any other, and a snackbar tells the person: *"1 message expired before it + could be sent"*. For a protocol round, the round is dropped and its manager is told, so the + session can re-propose or fail out loud rather than wait for nothing. Sending either one late + would publish something its own tag says should already be gone. +- The `sealGiftWrapPayload` debug log of the rumor JSON is removed (Phase 0, check 7). + +Tests (JVM, in `NostrNip17DaoJvmTest` or a new `DisappearingSendJvmTest`): every combination of +room override and default; protocol kinds at their floor, including with the policy Off; a +confederation statement keeping its single tag; the payload id equal to the rumor's id; wrap and +rumor expirations as D5 describes; the self-copy carrying the same rumor expiry; an expired +queued payload never reaching `BroadcastNostrEventRequest`. + +**Built.** One store, `DisappearingSettingsStore.stamp`, does the stamping. `sendChatMessage`, +`ChillDkgRitualManager.broadcast`, `ConfederationRitualManager.broadcast`, +`FrostSigningManager.broadcast` and `MarmotOutboundDao.deliveryWelcome` each call it before they +hash. The DKG and FROST producers stamp only on their NIP-17 branch. A Marmot room's rounds follow +the group's retention, as before. `FrostSigningManager` stamps again on each step of its +same-second id search, because the expiry is worked out from `created_at`. The wrap's tag uses +quartz's formula, and the seal stays empty. `persistAndBroadcastGiftWrap` records each wrap's +payload and expiry on its `GiftWrapMessage`. + +It differs from the plan in three ways: + +- `NostrEvent` has no `expiresAt` column. The predicate the plan relied on is on + `MarmotGroupEvent`. The wrap's row goes when the sweeper deletes its payload. +- An expired, unsent payload is left unsealed rather than reported to its manager. The sweeper + deletes it: a person's message at once, a round once its session lets it go. The count of + unsent messages comes back from each sweep (`Swept.unsent`). The snackbar for it is left to + Phase 6. +- The planned test that every producer stamps is covered for `sendChatMessage` in + `DisappearingSendJvmTest`. For the protocol producers it is covered by the full suite (1,866 + tests) passing with them stamping. There is no per-producer assertion yet. + +### Phase 4: receiving, and the sweeper + +- `GiftWrapSeal.decryptGiftWrapPayload` carries the rumor's tags through, as it already does. It + sets `GiftWrapPayload.expiresAt`, and `persistInboundChatMessage` sets `ChatMessage.expiresAt`. +- On arrival: if the rumor has already expired, nothing is filed, nothing is notified, no protocol + manager is handed it, and an `ExpiredGiftWrap` tombstone is written. The NIP-17 receive path + checks the tombstone before it decrypts. +- The notification classifier skips expired messages, and `NotificationDispatcher` cancels the + OS notification when a message is deleted. +- New `managers/DisappearingMessageSweeper`: + - `sweep(now)` hard-deletes, in one transaction, every expired written message (D6's list) and + every expired protocol payload that its `PayloadRetention` hook has released (Phase 5). It + returns what it deleted. + - It runs at app start, on returning to the foreground (`AppLifecycle`), in `BackgroundSyncPass`, + and from a timer set for the next `expiresAt` while the app is open. + - It prunes tombstones past their `dropAfter`. + - Until Phase 5 lands, protocol payloads are never released. The sweeper skips them, so + shipping Phase 4 alone deletes nothing a ceremony needs. +- Reply previews and quoting read through a lookup that turns a missing message into "This + message has disappeared". + +Tests: a JVM test of the sweeper for each row type; inbound drop and tombstone; a re-sync of a +tombstoned wrap not decrypting it; another sender's one-hour expiry being obeyed while this +device's setting is Off; the notification not being raised; a protocol payload past its expiry +but not released surviving a sweep. Add a case to `NotificationClassifierJvmTest`. + +**Built.** `DisappearingMessageSweeper.sweep` asks a `PayloadRetention` about each due payload. +Phase 4 ships `WrittenOnlyRetention`, which releases only what a person wrote. `sweepPayload`, a +transaction in `DisappearingDao`, does the deleting in this order: + +1. It clears any `ChatRoom.initialGiftWrapPayloadId` that points at the payload. +2. It deletes every wrap linked to the payload, plus the wrap around its seal for rows filed + before the link existed. The cascade takes each wrap's seal with it. +3. It deletes the payload, which takes its chat lines with it. + +Wraps that have no payload here go at their own expiry. `GizaRuntime.disappearing` runs the +sweeper. It watches the soonest `GiftWrapPayload.expiresAt`, wakes when that time comes and every +hour besides, and withdraws any notification that showed a deleted line +(`NotificationDispatcher.withdraw`). It starts beside `notifications`: in `GizaNavHost`, in +`StayConnectedService` and in the background pass's engines. `NotificationPolicy` drops an expired +line as `Reason.Expired`. + +It differs from the plan in one way. A message that arrives already expired is not deleted on +arrival. The sync that delivered it writes a request row against the event's id straight +afterwards, under a foreign key. So the arrival path deletes the seal, which is the part this +device could decrypt. It empties the wrap's content and keeps the empty row until the wrap's own +expiry, and the unlinked-wrap rule deletes it then. While the row is there, a re-sync finds the +event already stored and opens nothing. The tombstone lasts two days longer still, for a relay +that serves the wrap after it should have dropped it. + +Not needed: the "This message has disappeared" placeholder for a quoted line. In NIP-17 rooms +nothing sets or reads `ChatMessage.replyToMessageId` or `quotedMessageId` outside the model, so +no NIP-17 line quotes another. A group's direct messages do have replies, and Phase 7 deals with +those. + +### Phase 5: protocol payloads, released when their session is done + +- A `PayloadRetention` interface with `isReleased(database, payload): Boolean`, implemented by + each protocol that reads payloads back (Phase 0, check 6): + - **`ChillDkgRitualManager`**: released when the DKG session has completed or failed. + - **`FrostSigningManager`**: released when the signing session has a signature, a failure, or + has been abandoned. + - **`ConfederationRitualManager`**: released when the confederation's key ceremony has + completed, failed or been abandoned. Its statements are not on this path (Phase 0, check 6). + - **The Welcome**: released once the payload is sealed. Nothing reads a Welcome back. + - **Any other kind**: released when its expiry passes, which is the same rule as a written + message. +- The chat lines that protocol payloads render are deleted with them. +- The sweeper asks the hook for each expired protocol payload, and deletes it once the hook says + it is released. +- Tests: for each protocol, an open session keeps its expired payloads, and a finished one loses + them. A DKG run with the policy at its minimum still completes when one admin is offline for + six days. A signing session whose proposal expired off the relay is completed by a resend + (`frost-session-resend.md`). A formed confederation still reads as formed after its statements + have been swept. In `ChillDkg…JvmTest`, `CeremonyFollowThroughJvmTest`, + `ConfederationCeremonyJvmTest` and `ConfederationStatusTest`. + +**Built.** It is one `ProtocolRetention` object, not a hook on each manager. All three answers are +a lookup of the session that a round's session tag names. `GizaRuntime.disappearing` now runs the +sweeper with it in place of Phase 4's `WrittenOnlyRetention`. + +- A DKG round is released when its `DkgSession` is `COMPLETE` or `FAILED`. A signing round is + released when its `FrostSigningSession` is. A confederation-ceremony round is released when its + `ConfederationCeremony` is no longer `isRunning`. Abandoning a ceremony ends it as `FAILED`, so + that case is covered too. +- A round whose session this device does not have is released at its expiry. Nothing here will + read it back, and by the time its floor has passed, any session that was going to be made from + it has been. +- A Welcome is released at its expiry. An inbound Welcome is processed the moment it arrives, and + the only thing that refers back to one is the room's `initialGiftWrapPayloadId`, which the sweep + clears first. + +`ProtocolRetentionJvmTest` covers an open ceremony keeping its expired round, a completed one +losing it while the session's own record stays, a failed signing releasing its nonce, a round with +no session, a Welcome, and a written message. + +Not built, and left for the device run (Phase 8): the end-to-end tests that a DKG survives an admin +being offline for six days, and that a signing completes through a resend after its proposal has +expired off the relay. Both need two devices and a real relay, which the JVM tests do not model. +The confederation-status test is moot here, because statements do not travel on this path. + +### Phase 6: the screens + +Every point in CLAUDE.md applies: strings in `strings.xml` written in sentence case, spacing from +`MaterialTheme.spacing`, 48dp targets, icon descriptions decided, `ScreenStateTransition`, +`readableContent()`, and `NavigateBackButton` on pushed screens. + +- **Settings → "Disappearing messages"**: a new pushed screen and route. It has a radio list of + D3's presets and "Custom…", which opens a dialog with a number field and a unit selector, + checked against the bounds, with an inline error. Below the list are D7's two paragraphs and + D11's note about groups. Saving reports through `rememberNotifier`. +- **Conversation detail** (`ChatRoomDetailScreen`, NIP-17 rooms only): a "Disappearing messages" + row that shows "Default (1 day)", "Off" or a length, and opens the same picker with an extra + "Use default" option at the top. +- **Conversation**: the app-bar hourglass (D12), the per-message hourglass, the one-time notice + (D9), and the "disappeared" reply placeholder. +- Run `./gradlew :composeApp:m3Audit` with all budgets at zero. + +Tests: view-model JVM tests for the picker's validation and for override versus default, plus a +string-catalogue entry for every format string this adds. + +**Built.** + +- `DisappearingMessagesScreen` sits behind `DisappearingMessagesRoute(activeUserPublicKey, + chatRoomId?)`. It is reached from the profile screen, next to Notifications, for the default, + and from a NIP-17 room's detail screen for that room's override. It shows D3's presets as radio + rows, a custom dialog with a number field and a minutes/hours/days segmented row checked against + the bounds, and D7's and D11's paragraphs. +- The conversation shows `DisappearingTimerAction`, an hourglass in the app bar that opens the + room's setting, and `DisappearingNotice`, D9's one-time card. The transcript shows + `DisappearsIcon` beside an expiring line's time, with the time it goes as its description. +- `ChatRoomMessagingScreen` gets the store through a defaulted parameter that reads the running + `GizaRuntime`, so neither caller changed. A preview has no runtime and shows none of it. +- Lengths read in the largest whole unit ("1 week", "90 minutes"). `DisappearingLengthJvmTest` + covers that and the custom dialog's bounds. The m3, brand and wallet audits pass at their + budgets. + +It differs from the plan in three ways: + +- The room detail row shows a fixed description, not the current length. That screen reads the + room once, so a length shown there would go stale after a change. +- Nothing yet reports a message that expired before it could be sent. The sweeper counts these + (`Swept.unsent`), but there is no path from the runtime's sweeper to a screen's snackbar. +- The transcript lines a ceremony writes ("abandoned the shared key ceremony" and the like) are + local summaries. They have no `giftWrapPayloadId` and no expiry. So they show no hourglass, as + D12 says, but they are also not deleted with their rounds, which is less than D6 says. They hold + text the app wrote, not anybody's words. + +### Phase 7: when a group sends (D10) + +- `GroupDmSender` and `InboxReplies`: put the rumor expiration in at proposal time, show it on + the signing review, refuse out loud a proposal outside the bounds or missing its expiry, and + add the jittered wrap expiration when wrapping. +- The group's receive paths (`GroupDmReceiver` and the inbox's) obey the rumor expiry and use the + same sweeper. +- Tests in `GroupDmTodayJvmTest`, `InboxReplyJvmTest` and `FrostSigningDeclineJvmTest`, for the + out-of-bounds and missing-expiry refusals. + +All of this stays behind `groupDirectMessages` and `groupInbox`. + +**Built.** + +- **Sending.** `GroupDmSender.send` stamps the rumor with the proposer's policy before the seals + are built. `InboxReplies.build` takes a `disappearAfter`, and `propose` passes the policy. So the + expiry is inside what the quorum signs. +- **Wraps.** `GroupDmSender.wrapOwed` hands quartz the rumor's lifetime as its `expirationDelta`. + `InboxReplies.wrapAndOwe` reads the lifetime from the group's own copy and gives each wrap + `InboxWrap.wrap`'s new `expiration`. Both follow D5's formula. +- **Signer checks.** `GroupDmRefusal` and `InboxRefusal` refuse a rumor whose expiry is not a + length a person could choose (`DisappearingMessages.isAcceptableExpiry`), and say so. +- **Receiving.** `GroupDmReceiver` and `GroupInboxManager` do not file a message that is already + expired. They keep the wrap's ledger row with its words emptied, so a re-sync does not open the + message again. +- **Storage.** `GroupDmMessage` and `GroupInboxMessage` gain an `expiresAt`, read off their + `rumorJson`. They went into v50, which has not shipped, so `50.json` was regenerated rather than + adding a v51. +- **Sweeping.** `DisappearingDao.sweepGroupMessages` runs inside every sweep. It deletes the + expired messages, empties the words of the wraps that carried them, and drops whatever was + still owed to a relay: `GroupDmOutbound`, and `GroupInboxPublication` by signing session. + Inbox messages are swept only for written kinds. A confederation's statements are filed by + `ConfederationManager.recordStatement`, not as inbox messages, and they keep their own + `expiration` (D5). Phase 0's question about the confederation's stored status therefore does not + arise. + +It differs from the plan in two ways: + +- The signer cannot refuse a message that has no expiry, because it cannot know the proposer's + policy. Only an expiry outside the bounds is refused. +- The group's signed seals (`GroupSignedEvent`) are the signing session's record and are not + swept. A seal is ciphertext, but the group's admins can open it. + +Tests: `DisappearingGroupMessagesJvmTest` covers both conversation kinds, the emptied ledger row, +the dropped outbound row, and a statement surviving. `DisappearingMessagesTest` covers the signer +check and reading an expiry from JSON. The existing group DM and inbox tests pass with the +stamping in place. + +### Phase 8: the record, and devices + +A device run, written up under this phase: + +1. Giza ↔ Giza with the default: both sides delete the message after a day. Use a shortened custom + length for the run, then repeat once with the real default. +2. Giza ↔ Bennu: Bennu files the message, and Giza obeys an expiry that Bennu sends. +3. Giza ↔ another NIP-17 client: the message is still readable there, and Giza obeys the other + client's expiry. +4. After the wrap's expiration, query the relay directly and confirm it no longer serves the wrap. +5. A second device of the sender: the sender's half is readable there until the expiry. +6. Offline longer than the policy, both as sender and as recipient (the Phase 3 snackbar, and + D7's warning shown to be accurate). +7. A quorum DKG and a signing with the policy at 1 hour and one admin offline overnight. Both + finish, the signing through a resend. Afterwards the relay no longer serves their rounds, and + the device keeps the shares and the signature. +8. A mixed Giza–Bennu quorum running a signing, with expiring rounds. + +Then update the status line at the top of this document, note under each phase what was built and +where it differs from the plan, and add a short CLAUDE.md rule: *every NIP-17 payload goes +through `DisappearingMessages.stamp`, and a new kind gets a class in `classOf` with the reason for +its floor.* + +**Partly done.** The record is done: the status line, the notes under each phase, the CLAUDE.md +rule ("Everything sent in a NIP-17 wrap expires") and a row in the docs index. **The device run +has not been done**, so none of its eight steps has been seen working on a phone. Two points from +the earlier phases bear on it: + +- The DM relay describes itself as `nak serve`, "a local relay for testing" (Phase 0). Step 4 + shows what that relay does, which may not be what a production relay does. +- Steps 6 and 7 cover what the JVM tests cannot: a person told that their message expired before + it could be sent (not built, Phase 6), and ceremonies finishing across a real expiry. + +## What this does not do + +- It does not stop a recipient, another client or a relay from keeping a copy (D7). +- It does not change messages or rounds that were sent before it shipped (D9). +- It does not apply to Marmot rooms or Marmot direct messages (D11). +- It does not expire what a ceremony produces (keys, shares, signatures, session records). Only + the messages that carried the ceremony expire (D2). + +## Risks + +- **A ceremony that loses a round.** Protocol messages now leave the relay. A key ceremony that + outlasts its seven-day floor, or a signing whose resend never happens, ends up waiting for a + round that no longer exists. The floors (D2), Phase 0's fifth check and device-run step 7 are + the guard. Where there is no resend, as with DKG, the ceremony has to fail out loud when its + rounds have expired, never stall quietly. +- **Deleting state that is really a record.** If anything derives lasting state from protocol + payloads each time it is read, sweeping them erases that state. Confederation status is the + known suspect. Phase 0's sixth check finds the others, and Phase 5 does not release a protocol + until its result is stored. +- **Bennu refusing what it now receives.** Every protocol rumor gains a tag. A peer that validates + tags strictly could stop taking part in mixed groups. Phase 0's third check and device-run step + 8 cover this. +- **Messages the recipient never receives.** A recipient who stays offline longer than the policy + may never get the message. The default makes this a normal case rather than a rare one. D7 tells + people. Phase 8 measures how often it happens on a real relay. +- **A wrong clock.** A sender whose clock is behind sends messages that arrive already expired, and + D6 drops them. The 5-minute floor (D3) narrows this. It does not remove it. Log a dropped + message's lateness, so that a pattern can be seen. +- **A deletion that misses a copy.** Words stored somewhere the sweeper does not know about would + survive. Phase 0's seventh check, and a sweeper test for each table, guard against it. A new + table that stores message text should go through the sweeper's review. + +## Out of scope + +- A local "delete what I receive after…" retention (D1). +- Setting a Marmot group's retention from Giza (D11). +- Sending to the recipient's kind 10050 relays (D8). +- A resend for DKG rounds. If Phase 8 shows that the seven-day floor is not enough, that resend is + the follow-up, not a longer floor. + +## Order and size + +| Phase | Depends on | Size | +|---|---|---| +| 0 Checks | none | small | +| 1 Pin and pure core | 0 | small | +| 2 Storage | 1 | small | +| 3 Sending, every kind | 2 | medium | +| 4 Receiving and sweeper | 2 | medium | +| 5 Protocol release | 3, 4 | medium to large, depending on Phase 0's sixth check, and the largest risk | +| 6 Screens | 2 (3 and 4 to be useful) | medium | +| 7 Group sends | 3, 4 | medium | +| 8 Record and devices | all | small | + +Phases 3 and 4 can be built in parallel once Phase 2 has landed. Phase 6 can start on Phase 2's +store at the same time. Phase 3 can ship before Phase 5: protocol rounds then expire on the relay +but are never swept on the device, which is safe. The reverse order is not. + +## Checking the work + +```bash +./gradlew :composeApp:compileDebugKotlinAndroid :composeApp:jvmTest +``` + +```bash +./gradlew :composeApp:m3Audit +``` + +```bash +./gradlew check +```