From 58efd5ea2b147f7d9bef91b949b29ea4298976a8 Mon Sep 17 00:00:00 2001 From: MagicCodingMan Date: Mon, 30 Nov 2026 16:14:43 -0500 Subject: [PATCH 1/5] Add typed atomic conditional batches for protected records --- .../PublicApiBaseline.txt | 8 ++ .../MagicEncryptedQueryExtensions.cs | 4 +- .../Encryption/MagicProtectedBatch.cs | 89 ++++++++++++ Magic.IndexedDb/IndexDbManager.cs | 4 + Magic.IndexedDb/wwwroot/magicDB.js | 11 ++ .../wwwroot/utilities/protectedStorage.js | 63 +++++++++ docs/guides/managed-key-rotation.md | 38 +++++ tests/migrations/ProtectedWasm/App/App.razor | 10 ++ .../ProtectedWasm/App/ILLink.Descriptors.xml | 1 + tests/migrations/ProtectedWasm/App/Program.cs | 2 +- .../ProtectedWasm/Exporter/Program.cs | 2 +- tests/migrations/ProtectedWasm/Model.cs | 13 ++ .../ReleasedUpgrade/protected-batch.mjs | 131 ++++++++++++++++++ tests/migrations/ReleasedUpgrade/run.mjs | 8 +- 14 files changed, 379 insertions(+), 5 deletions(-) create mode 100644 Magic.IndexedDb/Encryption/MagicProtectedBatch.cs create mode 100644 tests/migrations/ReleasedUpgrade/protected-batch.mjs diff --git a/Magic.IndexedDb.UnitTests/PublicApiBaseline.txt b/Magic.IndexedDb.UnitTests/PublicApiBaseline.txt index 7bb2419..9de37a3 100644 --- a/Magic.IndexedDb.UnitTests/PublicApiBaseline.txt +++ b/Magic.IndexedDb.UnitTests/PublicApiBaseline.txt @@ -368,6 +368,14 @@ class Magic.IndexedDb.MagicProjectedQuery method System.Threading.Tasks.Task> ToListAsync(System.Threading.CancellationToken cancellationToken = null) static class Magic.IndexedDb.MagicProjectionExtensions method static Magic.IndexedDb.MagicProjectedQuery Select(Magic.IndexedDb.IMagicExecute source, System.Linq.Expressions.Expression> selector) +class Magic.IndexedDb.MagicProtectedBatch + ctor Magic.IndexedDb.MagicProtectedBatch() + method Magic.IndexedDb.MagicProtectedBatch Delete(Magic.IndexedDb.IMagicQuery table, T expected, System.Linq.Expressions.Expression> token) + method Magic.IndexedDb.MagicProtectedBatch ExpectAbsent(Magic.IndexedDb.IMagicQuery table, T record) + method Magic.IndexedDb.MagicProtectedBatch ExpectToken(Magic.IndexedDb.IMagicQuery table, T expected, System.Linq.Expressions.Expression> token) + method Magic.IndexedDb.MagicProtectedBatch Insert(Magic.IndexedDb.IMagicQuery table, T record) + method Magic.IndexedDb.MagicProtectedBatch Replace(Magic.IndexedDb.IMagicQuery table, T expected, System.Linq.Expressions.Expression> token, T replacement) + method System.Threading.Tasks.Task CommitAsync(System.Threading.CancellationToken cancellationToken = null) class Magic.IndexedDb.MagicTableTool ctor Magic.IndexedDb.MagicTableTool() class Magic.IndexedDb.MagicUniqueIndexAttribute : Magic.IndexedDb.Interfaces.IColumnNamed, System.Attribute diff --git a/Magic.IndexedDb/Encryption/MagicEncryptedQueryExtensions.cs b/Magic.IndexedDb/Encryption/MagicEncryptedQueryExtensions.cs index dd98768..d80b51a 100644 --- a/Magic.IndexedDb/Encryption/MagicEncryptedQueryExtensions.cs +++ b/Magic.IndexedDb/Encryption/MagicEncryptedQueryExtensions.cs @@ -105,7 +105,7 @@ private static async Task MutateIfCurrent(T item, JsonElement serialized) where T : class + internal static System.Text.Json.Nodes.JsonObject KeyOf(T item, JsonElement serialized) where T : class { var key = new System.Text.Json.Nodes.JsonObject(); foreach (var part in AttributeHelpers.GetPrimaryKeys(item)) @@ -113,7 +113,7 @@ private static System.Text.Json.Nodes.JsonObject KeyOf(T item, JsonElement se return key; } - private static MagicPropertyEntry MappedMember(Expression> member) + internal static MagicPropertyEntry MappedMember(Expression> member) { ArgumentNullException.ThrowIfNull(member); if (member.Body is not MemberExpression { Member: PropertyInfo property } access || diff --git a/Magic.IndexedDb/Encryption/MagicProtectedBatch.cs b/Magic.IndexedDb/Encryption/MagicProtectedBatch.cs new file mode 100644 index 0000000..3ca8889 --- /dev/null +++ b/Magic.IndexedDb/Encryption/MagicProtectedBatch.cs @@ -0,0 +1,89 @@ +using System.Linq.Expressions; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using Magic.IndexedDb.Helpers; +using Magic.IndexedDb.LinqTranslation.Models; + +namespace Magic.IndexedDb; + +/// Builds an atomic conditional operation across protected tables in one managed database. +public sealed class MagicProtectedBatch +{ + private readonly JsonArray _entries = new(); + private IndexedDbManager? _manager; + private string? _database; + private bool _hasWrites; + + /// Requires the exact key represented by the supplied record to be absent. + public MagicProtectedBatch ExpectAbsent(IMagicQuery table, T record) where T : class => + Add(table, record, null, "check", null); + + /// Requires a row to have the supplied value of a direct persisted property. + public MagicProtectedBatch ExpectToken(IMagicQuery table, T expected, + Expression> token) where T : class => + Add(table, expected, token, "check", null); + + /// Inserts a record if its primary key is absent. + public MagicProtectedBatch Insert(IMagicQuery table, T record) where T : class => + Add(table, record, null, "insert", record); + + /// Replaces a record if its token matches. The primary key must remain the same. + public MagicProtectedBatch Replace(IMagicQuery table, T expected, + Expression> token, T replacement) where T : class + { + ArgumentNullException.ThrowIfNull(replacement); + return Add(table, expected, token, "replace", replacement); + } + + /// Deletes a record if its token matches. + public MagicProtectedBatch Delete(IMagicQuery table, T expected, + Expression> token) where T : class => + Add(table, expected, token, "delete", null); + + /// Commits all mutations or returns a conflict without writing any of them. + public async Task CommitAsync(CancellationToken cancellationToken = default) + { + if (!_hasWrites || _manager is null || _database is null) + throw new InvalidOperationException("A protected batch requires a mutation."); + + var json = _entries.ToJsonString(); + if (Encoding.UTF8.GetByteCount(json) > 2 * 1024 * 1024) + throw new InvalidOperationException("A protected batch cannot exceed 2 MiB of serialized arguments."); + using var payload = JsonDocument.Parse(json); + return await _manager.ConditionalProtectedBatchAsync(_database, payload.RootElement.Clone(), cancellationToken) + ? MagicConditionalMutationResult.Applied : MagicConditionalMutationResult.Conflict; + } + + private MagicProtectedBatch Add(IMagicQuery source, T expected, + Expression>? token, string operation, T? replacement) where T : class + { + ArgumentNullException.ThrowIfNull(expected); + if (source is not MagicQuery query || (_manager is not null && + (_manager != query.Manager || _database != query.DatabaseName))) + throw new ArgumentException("All tables must belong to the same managed database context.", nameof(source)); + if (_entries.Count == 32) + throw new InvalidOperationException("A protected batch can include at most 32 rows."); + if (token is null && operation is "replace" or "delete") + throw new ArgumentNullException(nameof(token)); + + var settings = query.Manager.Settings(query.DatabaseName); + var serialized = MagicSerializationHelper.SerializeObjectToJsonElement(expected, settings); + var member = token is null ? null : MagicEncryptedQueryExtensions.MappedMember(token).JsPropertyName; + var entry = new JsonObject + { + ["store"] = query.SchemaName, + ["key"] = MagicEncryptedQueryExtensions.KeyOf(expected, serialized), + ["member"] = member, + ["expected"] = member is null ? null : JsonNode.Parse(serialized.GetProperty(member).GetRawText()), + ["operation"] = operation, + ["replacement"] = replacement is null ? null : JsonNode.Parse( + MagicSerializationHelper.SerializeObjectToJsonElement(replacement, settings).GetRawText()) + }; + _entries.Add(entry); + _manager = query.Manager; + _database = query.DatabaseName; + _hasWrites |= operation != "check"; + return this; + } +} diff --git a/Magic.IndexedDb/IndexDbManager.cs b/Magic.IndexedDb/IndexDbManager.cs index 01ba212..1a18ff9 100644 --- a/Magic.IndexedDb/IndexDbManager.cs +++ b/Magic.IndexedDb/IndexDbManager.cs @@ -383,6 +383,10 @@ internal Task ConditionalProtectedMutationAsync(MagicQuery query, st new TypedArgument(workspaceStore), new TypedArgument(payload.RootElement.Clone())); } + internal Task ConditionalProtectedBatchAsync(string database, JsonElement entries, CancellationToken token) => + Invocation(database).CallJsAsync(Cache.MagicDbJsImportPath, "conditionalProtectedBatch", token, + new TypedArgument(Route(database)), new TypedArgument(entries)); + internal async Task DeleteAsync(T item, string dbName, CancellationToken cancellationToken = default) where T : class { string schemaName = SchemaHelper.GetTableName(); diff --git a/Magic.IndexedDb/wwwroot/magicDB.js b/Magic.IndexedDb/wwwroot/magicDB.js index 7d8ff15..d83488b 100644 --- a/Magic.IndexedDb/wwwroot/magicDB.js +++ b/Magic.IndexedDb/wwwroot/magicDB.js @@ -628,6 +628,17 @@ export function conditionalProtectedMutation(name, store, workspaceStore, { reco return table.conditionalMutation(record, revision, workspace, generation, replacement); } +export function conditionalProtectedBatch(name, entries) { + if (!Array.isArray(entries) || entries.length < 1 || entries.length > 32) + throw new Error("MAGIC_CONDITIONAL_WRITE_UNSUPPORTED: Expected 1 to 32 batch rows."); + const rows = entries.map(entry => { + const table = protectedTable(name, entry.store); + if (!table) throw new Error("MAGIC_CONDITIONAL_WRITE_UNSUPPORTED: Protected tables are required."); + return { ...entry, table }; + }); + return rows[0].table.conditionalBatch(rows); +} + export function patchPublicRecord(name, store, key, changes) { const table = protectedTable(name, store); if (!table) throw new Error("A public patch requires a protected table."); diff --git a/Magic.IndexedDb/wwwroot/utilities/protectedStorage.js b/Magic.IndexedDb/wwwroot/utilities/protectedStorage.js index ad9d893..86d3f16 100644 --- a/Magic.IndexedDb/wwwroot/utilities/protectedStorage.js +++ b/Magic.IndexedDb/wwwroot/utilities/protectedStorage.js @@ -372,6 +372,69 @@ class ProtectedTable { }); } + conditionalBatch(entries) { + const unsupported = message => new Error(`MAGIC_CONDITIONAL_WRITE_UNSUPPORTED: ${message}`); + const rows = []; + const tables = new Map(); + for (const { table, key, member, expected, operation, replacement } of entries) { + if (!table.managed || table.db !== this.db) + throw unsupported("Conditions require one protected managed database."); + if (member !== null) { + validateMember(member); + if (typeof expected !== "string" && !Number.isSafeInteger(expected)) + throw unsupported("Expected tokens must be strings or safe integers."); + } + if (!(operation === "check" || + (operation === "insert" && member === null && replacement !== null) || + (operation === "replace" && member !== null && replacement !== null) || + (operation === "delete" && member !== null && replacement === null))) + throw unsupported("The mutation requires a matching target guard."); + const primaryKey = table.key(key); + indexedDB.cmp(primaryKey, primaryKey); + if (rows.some(row => row.table.table.name === table.table.name && + indexedDB.cmp(row.primaryKey, primaryKey) === 0)) + throw unsupported("Represent each store and primary key once."); + if (replacement !== null && indexedDB.cmp(primaryKey, table.key(replacement)) !== 0) + throw unsupported("A replacement must retain the primary key."); + rows.push({ table, primaryKey, member, expected, operation, replacement }); + if (table.table.name !== this.table.name) tables.set(table.table.name, table.table); + } + if (!rows.some(row => row.operation !== "check")) + throw unsupported("A batch requires a mutation."); + + return this.access(async (keys, assertCurrent) => { + await this.assertPolicy(true); + for (const row of rows) { + assertCurrent(); + row.snapshot = await row.table.table.get(row.primaryKey); + if (row.member === null) { + if (row.snapshot !== undefined) return false; + } else { + if (row.snapshot === undefined) return false; + const opened = await row.table.openStoredRecord(row.snapshot, row.primaryKey, keys); + if (!Object.hasOwn(opened, row.member) || opened[row.member] !== row.expected) return false; + } + if (row.replacement !== null) { + row.sealed = await sealRecord(row.replacement, row.table.policy, keys.key, keys.keyId, + row.table.context(row.primaryKey)); + } + } + assertCurrent(); + return this.fencedWrite(async () => { + for (const row of rows) { + if (!sameStoredValue(row.snapshot, await row.table.table.get(row.primaryKey))) return false; + } + assertCurrent(); + for (const row of rows) { + if (row.operation === "insert") await row.table.table.add(row.sealed); + else if (row.operation === "replace") await row.table.table.put(row.sealed); + else if (row.operation === "delete") await row.table.table.delete(row.primaryKey); + } + return true; + }, assertCurrent, [...tables.values()]); + }); + } + async patch(primaryKey, changes) { const names = Object.keys(changes); for (const name of names) validateMember(name); diff --git a/docs/guides/managed-key-rotation.md b/docs/guides/managed-key-rotation.md index 2456297..949352b 100644 --- a/docs/guides/managed-key-rotation.md +++ b/docs/guides/managed-key-rotation.md @@ -141,3 +141,41 @@ Full trimming still requires the app to preserve persisted model members used through reflection. Root the relevant model types in the application linker descriptor and mark infrastructure-only properties with `[MagicNotMapped]` so the exporter and runtime agree on the persisted schema. + +### Conditional batches across protected stores + +Use `MagicProtectedBatch` for coordinated changes inside one unlocked, managed +database. Each entry addresses an exact primary key. Query filters and ordering do +not participate. Guard-only entries use `ExpectAbsent` or `ExpectToken`. Insert +implies an absence guard. Replace and delete require a token guard on the target. + +```csharp +var result = await new MagicProtectedBatch() + .ExpectToken(documents, expectedDocument, row => row.Revision) + .ExpectToken(epochs, expectedEpoch, row => row.Generation) + .Insert(references, newReference) + .Replace(referenceStates, expectedState, row => row.Revision, updatedState) + .CommitAsync(cancellationToken); +``` + +The example assumes that every writer updates the authoritative reference state +with its reference mutation. An eviction can guard the epoch and delete both +the document and its zero-reference state in one batch. Build the new batch from +fresh state after a conflict. If a key can be reused, use a fresh token for each +incarnation. Existing writers that bypass the reference state must be fenced +before relying on it for eviction. + +One batch accepts up to 32 distinct rows and 2 MiB of serialized arguments. +Specify each store and primary key once, including rows used only as guards. +Use direct persisted string tokens or tokens that encode as JavaScript safe +integers. Magic checks tokens against authenticated records and compares their +stored snapshots again inside a single read-write transaction. If a guard fails, +the result is `Conflict`. Storage, authorization, and format errors are failures, +and the browser rolls back an aborted transaction. + +The batch snapshots its arguments as entries are added. Use a new builder for +each attempt. Protected data is processed in browser memory before opening the +write transaction. Larger batches hold more snapshots and ciphertext in memory +and lock more stores for longer. Keep each batch scoped to one logical change. +Cancellation of the .NET wait does not establish that a previously dispatched +browser transaction aborted. Re-read the affected state if the outcome is unclear. diff --git a/tests/migrations/ProtectedWasm/App/App.razor b/tests/migrations/ProtectedWasm/App/App.razor index 1e202f4..407ae9e 100644 --- a/tests/migrations/ProtectedWasm/App/App.razor +++ b/tests/migrations/ProtectedWasm/App/App.razor @@ -128,6 +128,16 @@ table, oldFence, row => row.Generation) == MagicConditionalMutationResult.Applied, "The fence could not advance itself."); Require(await table.InsertProtectedIfCurrentAsync(new RotationRow { Id = 4, Secret = "Stale generation" }, table, oldFence, row => row.Generation) == MagicConditionalMutationResult.Conflict, "The retired generation inserted a record."); + var references = await database.Query(); + var reference = new ReferenceRow { Id = 1, Target = "document" }; + Require(await new MagicProtectedBatch().ExpectToken(table, oldFence, row => row.Generation) + .Insert(references, reference).CommitAsync() == MagicConditionalMutationResult.Conflict, + "A retired fence allowed a batch insert."); + Require(await new MagicProtectedBatch().ExpectToken(table, advancedFence, row => row.Generation) + .Insert(references, reference).CommitAsync() == MagicConditionalMutationResult.Applied, + "The cross-store batch insert failed."); + Require((await references.ToListAsync()).Single().Target == "document", + "The protected batch failed to persist the typed value."); var ready = await context.KeyRotation.GetKeyRotationStatusAsync(records); Require(ready.Phase == MagicKeyRotationPhase.NotStarted && ready.ReadsAllowed && ready.WritesAllowed && !ready.RetirementReady, "A ready vault reported incorrect availability before its first rotation."); diff --git a/tests/migrations/ProtectedWasm/App/ILLink.Descriptors.xml b/tests/migrations/ProtectedWasm/App/ILLink.Descriptors.xml index 3b26052..11a0b6b 100644 --- a/tests/migrations/ProtectedWasm/App/ILLink.Descriptors.xml +++ b/tests/migrations/ProtectedWasm/App/ILLink.Descriptors.xml @@ -2,5 +2,6 @@ + diff --git a/tests/migrations/ProtectedWasm/App/Program.cs b/tests/migrations/ProtectedWasm/App/Program.cs index c766fd8..a437018 100644 --- a/tests/migrations/ProtectedWasm/App/Program.cs +++ b/tests/migrations/ProtectedWasm/App/Program.cs @@ -5,7 +5,7 @@ var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add("#app"); builder.Services.AddMagicBlazorDB(BlazorInteropMode.WASM, false, - [typeof(ProtectedRow), typeof(RotationRow)], [typeof(ProtectedRepository)]); + [typeof(ProtectedRow), typeof(RotationRow), typeof(ReferenceRow)], [typeof(ProtectedRepository)]); builder.Services.AddMagicIndexedDbEncryption(_ => [new MagicEncryptionOptions("protected-wasm", "published-account", "fixture-key") { PhysicalDatabaseName = ProtectedRepository.PhysicalName }]); diff --git a/tests/migrations/ProtectedWasm/Exporter/Program.cs b/tests/migrations/ProtectedWasm/Exporter/Program.cs index 5d7fc41..de90f00 100644 --- a/tests/migrations/ProtectedWasm/Exporter/Program.cs +++ b/tests/migrations/ProtectedWasm/Exporter/Program.cs @@ -1,4 +1,4 @@ using Magic.IndexedDb.Migrations; -return MagicSchemaExporter.Run(args, [typeof(ProtectedRow), typeof(RotationRow)], [typeof(ProtectedRepository)], +return MagicSchemaExporter.Run(args, [typeof(ProtectedRow), typeof(RotationRow), typeof(ReferenceRow)], [typeof(ProtectedRepository)], new MagicSchemaOptions { ProtectedDatabases = ["protected-wasm", "rotation-wasm"] }); diff --git a/tests/migrations/ProtectedWasm/Model.cs b/tests/migrations/ProtectedWasm/Model.cs index 9af73f8..674a0a9 100644 --- a/tests/migrations/ProtectedWasm/Model.cs +++ b/tests/migrations/ProtectedWasm/Model.cs @@ -42,3 +42,16 @@ public sealed class RotationRow : MagicTableTool, IMagicTable, IMagicTable +{ + [MagicNotMapped] + public ProtectedRepository Databases { get; } = new(); + public IndexedDbSet GetDefaultDatabase() => ProtectedRepository.RotationRecords; + public string GetTableName() => "references"; + public IMagicCompoundKey GetKeys() => CreatePrimaryKey(row => row.Id, false); + public List GetCompoundIndexes() => []; + public int Id { get; set; } + public string Target { get; set; } = ""; +} diff --git a/tests/migrations/ReleasedUpgrade/protected-batch.mjs b/tests/migrations/ReleasedUpgrade/protected-batch.mjs new file mode 100644 index 0000000..2225734 --- /dev/null +++ b/tests/migrations/ReleasedUpgrade/protected-batch.mjs @@ -0,0 +1,131 @@ +import assert from 'node:assert/strict'; + +export async function exerciseProtectedBatch(context, origin) { + const manifestUrl = new URL('/releases/rotation/rotation-wasm/manifest.json', origin).href; + const documents = 'rotation-records'; + const references = 'references'; + const route = '__magic_protected__:batch-fixture'; + const open = async initialize => { + const page = await context.newPage(); + assert.ok((await page.goto(manifestUrl)).ok()); + await page.evaluate(async ({ manifestUrl, route, documents, references, initialize }) => { + window.batchApi = await import('/_content/Magic.IndexedDb/magicDB.js'); + const manifest = await (await fetch(manifestUrl)).json(); + const target = manifest.schemas.find(item => item.revision === manifest.targetRevision); + const model = await (await fetch(new URL(target.path, manifestUrl))).json(); + await batchApi.createDb({ + name: route, + migrationManifestUrl: manifestUrl, migrationSchema: model, + encryption: { account: 'batch-test', physicalName: route, explicitPhysicalBinding: true }, + storeSchemas: [documents, references].map(tableName => ({ + tableName, primaryKeyAuto: false, columnNamesInCompoundKey: ['Id'], + indexes: ['Id'], uniqueIndexes: [], columnNamesInCompoundIndex: [], exposedFields: ['Id'] + })) + }); + await batchApi.unlockProtectedDatabase(route, 'batch-key', new Uint8Array(32).fill(79), initialize); + await batchApi.ensureProtectedMigration(route); + }, { manifestUrl, route, documents, references, initialize }); + return page; + }; + + const tabA = await open(true); + const tabB = await open(false); + const write = (page, storeName, record) => + page.evaluate(({ route, storeName, record }) => batchApi.addItem({ dbName: route, storeName, record }), + { route, storeName, record }); + const read = (page, store, key) => + page.evaluate(({ route, store, key }) => batchApi.findItem(route, store, key), { route, store, key }); + const commit = (page, entries) => + page.evaluate(({ route, entries }) => batchApi.conditionalProtectedBatch(route, entries), { route, entries }); + const entry = (store, Id, operation, member = null, expected = null, replacement = null) => + ({ store, key: { Id }, operation, member, expected, replacement }); + + await write(tabA, documents, { Id: 100, Revision: 1, Generation: 7, Secret: 'Epoch' }); + const epoch = entry(documents, 100, 'check', 'Generation', 7); + for (const [id, saveFirst] of [[1, true], [3, false]]) { + const marker = id + 1; + await write(tabA, documents, { Id: id, Revision: 1, Secret: 'Prepared document' }); + await write(tabA, documents, { Id: marker, Revision: 1, Generation: 0, Secret: 'Reference count' }); + // Both tabs finish making their decision before either tab is allowed to write. + async function prepare(page) { + const [record, state, fence] = await Promise.all([ + read(page, documents, id), read(page, documents, marker), read(page, documents, 100) + ]); + assert.equal(record.Revision, 1); + assert.equal(state.Generation, 0); + assert.equal(fence.Generation, 7); + } + await Promise.all([prepare(tabA), prepare(tabB)]); + const eviction = [epoch, entry(documents, id, 'delete', 'Revision', 1), + entry(documents, marker, 'delete', 'Revision', 1)]; + const save = [epoch, entry(documents, id, 'check', 'Revision', 1), + entry(references, id, 'insert', null, null, { Id: id, Target: 'Secret reference' }), + entry(documents, marker, 'replace', 'Revision', 1, + { Id: marker, Revision: 2, Generation: 1, Secret: 'Reference count' })]; + if (saveFirst) { + assert.equal(await commit(tabB, save), true); + assert.equal(await commit(tabA, eviction), false); + assert.equal((await read(tabA, documents, marker)).Generation, 1); + assert.equal((await read(tabA, references, id)).Target, 'Secret reference'); + } else { + assert.equal(await commit(tabA, eviction), true); + assert.equal(await commit(tabB, save), false); + assert.ok(!await read(tabB, references, id)); + assert.ok(!await read(tabB, documents, marker)); + await write(tabA, documents, { Id: id, Revision: 9, Secret: 'Different incarnation' }); + assert.equal(await commit(tabB, save), false); + } + } + + const aborted = await tabA.evaluate(async ({ route, documents, references, epoch }) => { + const original = IDBObjectStore.prototype.add; + let staged = false; + IDBObjectStore.prototype.add = function (...args) { + const request = original.apply(this, args); + if (this.name === references && args[0].Id === 99) { + request.addEventListener('success', () => { + staged = true; + this.transaction.abort(); + }); + } + return request; + }; + try { + await batchApi.conditionalProtectedBatch(route, [ + epoch, + { store: documents, key: { Id: 1 }, operation: 'replace', member: 'Revision', expected: 1, + replacement: { Id: 1, Revision: 2, Secret: 'Must roll back' } }, + { store: references, key: { Id: 99 }, operation: 'insert', member: null, expected: null, + replacement: { Id: 99, Target: 'Must roll back' } } + ]); + return false; + } catch { + return staged; + } finally { + IDBObjectStore.prototype.add = original; + } + }, { route, documents, references, epoch }); + assert.equal(aborted, true, 'The native transaction must abort after staging its final write.'); + await tabA.close(); + await tabB.close(); + + const reopened = await open(false); + assert.equal((await read(reopened, documents, 1)).Secret, 'Prepared document'); + assert.equal((await read(reopened, references, 1)).Target, 'Secret reference'); + assert.ok(!await read(reopened, references, 99)); + const raw = await reopened.evaluate(({ route, references }) => new Promise((resolve, reject) => { + const request = indexedDB.open(route); + request.onerror = () => reject(request.error); + request.onsuccess = () => { + const db = request.result; + const get = db.transaction(references).objectStore(references).get(1); + get.onsuccess = () => { + db.close(); + resolve(Object.keys(get.result).sort()); + }; + get.onerror = () => reject(get.error); + }; + }), { route, references }); + assert.deepEqual(raw, ['Id', '__magic_record']); + await reopened.close(); +} diff --git a/tests/migrations/ReleasedUpgrade/run.mjs b/tests/migrations/ReleasedUpgrade/run.mjs index 3af2dcc..1f29cf2 100644 --- a/tests/migrations/ReleasedUpgrade/run.mjs +++ b/tests/migrations/ReleasedUpgrade/run.mjs @@ -1,4 +1,5 @@ import assert from 'node:assert/strict'; +import { exerciseProtectedBatch } from './protected-batch.mjs'; import { platform, release, arch, version as osVersion } from 'node:os'; import { execFileSync } from 'node:child_process'; import { createServer } from 'node:http'; @@ -106,7 +107,7 @@ async function load(context, query = '') { const results = []; const cutoverCases = versions.includes('2.0.7') ? ['uncooperative-v2-writer', 'cooperative-v2-bridge'] : []; -const expected = versions.length + cutoverCases.length + 2 + (versions.includes('2.0.7') ? 2 : 0); +const expected = versions.length + cutoverCases.length + 3 + (versions.includes('2.0.7') ? 2 : 0); async function runCase(name, action) { const result = { name, state: 'failed' }; @@ -281,6 +282,11 @@ try { } }); + await runCase('atomic-protected-batches-in-two-tabs', async context => { + deployment = buildMode + '/protected'; + await exerciseProtectedBatch(context, origin); + }); + if (versions.includes('2.0.7')) for (const legacyProtected of [false, true]) { const scenario = legacyProtected ? 'released-numeric-vault' : 'released-numeric-enrollment'; await runCase(scenario, async (context, result) => { From 9b2a48e64a0c4177ef81d8eaa2dcc4799c90a0c5 Mon Sep 17 00:00:00 2001 From: MagicCodingMan Date: Mon, 30 Nov 2026 16:15:25 -0500 Subject: [PATCH 2/5] Require authenticated encrypted tokens in conditional batches --- Magic.IndexedDb/wwwroot/utilities/protectedStorage.js | 7 +++++-- docs/guides/managed-key-rotation.md | 4 ++-- tests/migrations/ReleasedUpgrade/protected-batch.mjs | 8 ++++++++ 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/Magic.IndexedDb/wwwroot/utilities/protectedStorage.js b/Magic.IndexedDb/wwwroot/utilities/protectedStorage.js index 86d3f16..a73981b 100644 --- a/Magic.IndexedDb/wwwroot/utilities/protectedStorage.js +++ b/Magic.IndexedDb/wwwroot/utilities/protectedStorage.js @@ -377,14 +377,17 @@ class ProtectedTable { const rows = []; const tables = new Map(); for (const { table, key, member, expected, operation, replacement } of entries) { - if (!table.managed || table.db !== this.db) + if (!table.managed || table.db !== this.db || + (table.policy.exposed === null && table.policy.fields.size === 0)) throw unsupported("Conditions require one protected managed database."); if (member !== null) { validateMember(member); + if (table.isPublic(member)) + throw unsupported("Batch tokens must be encrypted persisted members."); if (typeof expected !== "string" && !Number.isSafeInteger(expected)) throw unsupported("Expected tokens must be strings or safe integers."); } - if (!(operation === "check" || + if (!((operation === "check" && replacement === null) || (operation === "insert" && member === null && replacement !== null) || (operation === "replace" && member !== null && replacement !== null) || (operation === "delete" && member !== null && replacement === null))) diff --git a/docs/guides/managed-key-rotation.md b/docs/guides/managed-key-rotation.md index 949352b..a799cd9 100644 --- a/docs/guides/managed-key-rotation.md +++ b/docs/guides/managed-key-rotation.md @@ -167,8 +167,8 @@ before relying on it for eviction. One batch accepts up to 32 distinct rows and 2 MiB of serialized arguments. Specify each store and primary key once, including rows used only as guards. -Use direct persisted string tokens or tokens that encode as JavaScript safe -integers. Magic checks tokens against authenticated records and compares their +Use direct encrypted members as tokens. Their values must encode as strings +or JavaScript safe integers. Magic authenticates those values and compares the stored snapshots again inside a single read-write transaction. If a guard fails, the result is `Conflict`. Storage, authorization, and format errors are failures, and the browser rolls back an aborted transaction. diff --git a/tests/migrations/ReleasedUpgrade/protected-batch.mjs b/tests/migrations/ReleasedUpgrade/protected-batch.mjs index 2225734..8b23d61 100644 --- a/tests/migrations/ReleasedUpgrade/protected-batch.mjs +++ b/tests/migrations/ReleasedUpgrade/protected-batch.mjs @@ -77,6 +77,14 @@ export async function exerciseProtectedBatch(context, origin) { } } + const insert = entry(references, 98, 'insert', null, null, { Id: 98, Target: 'Must not commit' }); + await assert.rejects(() => commit(tabA, [epoch, epoch, insert]), /Represent each store and primary key once/); + await assert.rejects(() => commit(tabA, [entry(documents, 100, 'check', 'Id', 100), insert]), + /Batch tokens must be encrypted/); + assert.equal(await commit(tabA, [entry(documents, 100, 'check', 'Generation', 8), insert]), false); + assert.equal(await commit(tabA, [entry(documents, 1, 'check'), insert]), false); + assert.ok(!await read(tabA, references, 98)); + const aborted = await tabA.evaluate(async ({ route, documents, references, epoch }) => { const original = IDBObjectStore.prototype.add; let staged = false; From c332252aa5b056f1ddc728b2e80406c07580244c Mon Sep 17 00:00:00 2001 From: MagicCodingMan Date: Mon, 30 Nov 2026 16:15:48 -0500 Subject: [PATCH 3/5] Exercise the late protected snapshot recheck in a second tab --- docs/guides/managed-key-rotation.md | 7 +++-- .../ReleasedUpgrade/protected-batch.mjs | 29 ++++++++++++++++++- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/docs/guides/managed-key-rotation.md b/docs/guides/managed-key-rotation.md index a799cd9..8d40028 100644 --- a/docs/guides/managed-key-rotation.md +++ b/docs/guides/managed-key-rotation.md @@ -161,8 +161,8 @@ var result = await new MagicProtectedBatch() The example assumes that every writer updates the authoritative reference state with its reference mutation. An eviction can guard the epoch and delete both the document and its zero-reference state in one batch. Build the new batch from -fresh state after a conflict. If a key can be reused, use a fresh token for each -incarnation. Existing writers that bypass the reference state must be fenced +fresh state after a conflict. Change tokens on every logical replacement and each new incarnation of a reused +key. Existing writers that bypass the reference state must be fenced before relying on it for eviction. One batch accepts up to 32 distinct rows and 2 MiB of serialized arguments. @@ -178,4 +178,5 @@ each attempt. Protected data is processed in browser memory before opening the write transaction. Larger batches hold more snapshots and ciphertext in memory and lock more stores for longer. Keep each batch scoped to one logical change. Cancellation of the .NET wait does not establish that a previously dispatched -browser transaction aborted. Re-read the affected state if the outcome is unclear. +browser transaction aborted. Re-read the affected rows and reconcile whether that exact operation committed +before retrying. diff --git a/tests/migrations/ReleasedUpgrade/protected-batch.mjs b/tests/migrations/ReleasedUpgrade/protected-batch.mjs index 8b23d61..4d89b2f 100644 --- a/tests/migrations/ReleasedUpgrade/protected-batch.mjs +++ b/tests/migrations/ReleasedUpgrade/protected-batch.mjs @@ -85,6 +85,33 @@ export async function exerciseProtectedBatch(context, origin) { assert.equal(await commit(tabA, [entry(documents, 1, 'check'), insert]), false); assert.ok(!await read(tabA, references, 98)); + // Pause at sealing the new reference, after the epoch snapshot was + // authenticated and before the first tab can open its write transaction. + await tabA.evaluate(() => { + const original = SubtleCrypto.prototype.encrypt; + let resume; + const resumed = new Promise(resolve => { resume = resolve; }); + let markPaused; + window.batchPaused = new Promise(resolve => { markPaused = resolve; }); + window.resumeBatch = resume; + SubtleCrypto.prototype.encrypt = async function (...args) { + SubtleCrypto.prototype.encrypt = original; + markPaused(); + await resumed; + return original.apply(this, args); + }; + }); + const racing = commit(tabA, [epoch, insert]); + try { + await tabA.evaluate(() => batchPaused); + assert.equal(await commit(tabB, [entry(documents, 100, 'replace', 'Generation', 7, + { Id: 100, Revision: 2, Generation: 8, Secret: 'New epoch' })]), true); + } finally { + await tabA.evaluate(() => resumeBatch()); + } + assert.equal(await racing, false, 'A guard changed after authentication and before native commit.'); + assert.ok(!await read(tabA, references, 98), 'The stale snapshot must leave zero writes.'); + const aborted = await tabA.evaluate(async ({ route, documents, references, epoch }) => { const original = IDBObjectStore.prototype.add; let staged = false; @@ -112,7 +139,7 @@ export async function exerciseProtectedBatch(context, origin) { } finally { IDBObjectStore.prototype.add = original; } - }, { route, documents, references, epoch }); + }, { route, documents, references, epoch: { ...epoch, expected: 8 } }); assert.equal(aborted, true, 'The native transaction must abort after staging its final write.'); await tabA.close(); await tabB.close(); From 5afa1a3549a48d6972e9901e5c03257841115f83 Mon Sep 17 00:00:00 2001 From: MagicCodingMan Date: Mon, 30 Nov 2026 16:20:52 -0500 Subject: [PATCH 4/5] Qualify the typed batch on the reopened target-key vault --- tests/migrations/ProtectedWasm/App/App.razor | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/tests/migrations/ProtectedWasm/App/App.razor b/tests/migrations/ProtectedWasm/App/App.razor index 407ae9e..f9ba7f5 100644 --- a/tests/migrations/ProtectedWasm/App/App.razor +++ b/tests/migrations/ProtectedWasm/App/App.razor @@ -128,16 +128,6 @@ table, oldFence, row => row.Generation) == MagicConditionalMutationResult.Applied, "The fence could not advance itself."); Require(await table.InsertProtectedIfCurrentAsync(new RotationRow { Id = 4, Secret = "Stale generation" }, table, oldFence, row => row.Generation) == MagicConditionalMutationResult.Conflict, "The retired generation inserted a record."); - var references = await database.Query(); - var reference = new ReferenceRow { Id = 1, Target = "document" }; - Require(await new MagicProtectedBatch().ExpectToken(table, oldFence, row => row.Generation) - .Insert(references, reference).CommitAsync() == MagicConditionalMutationResult.Conflict, - "A retired fence allowed a batch insert."); - Require(await new MagicProtectedBatch().ExpectToken(table, advancedFence, row => row.Generation) - .Insert(references, reference).CommitAsync() == MagicConditionalMutationResult.Applied, - "The cross-store batch insert failed."); - Require((await references.ToListAsync()).Single().Target == "document", - "The protected batch failed to persist the typed value."); var ready = await context.KeyRotation.GetKeyRotationStatusAsync(records); Require(ready.Phase == MagicKeyRotationPhase.NotStarted && ready.ReadsAllowed && ready.WritesAllowed && !ready.RetirementReady, "A ready vault reported incorrect availability before its first rotation."); @@ -188,6 +178,16 @@ table = await database.Query(); var rows = await table.ToListAsync(); Require(rows.Count == 3 && rows.All(row => row.Secret == "Document " + row.Id), "Rotation changed typed data."); + var references = await database.Query(); + var reference = new ReferenceRow { Id = 1, Target = "document" }; + Require(await new MagicProtectedBatch().ExpectToken(table, oldFence, row => row.Generation) + .Insert(references, reference).CommitAsync() == MagicConditionalMutationResult.Conflict, + "A retired fence allowed a batch insert."); + Require(await new MagicProtectedBatch().ExpectToken(table, advancedFence, row => row.Generation) + .Insert(references, reference).CommitAsync() == MagicConditionalMutationResult.Applied, + "The cross-store batch insert failed."); + Require((await references.ToListAsync()).Single().Target == "document", + "The protected batch failed to persist the typed value."); await Contexts.DeactivateAsync(); } From 0be47a991baa650c1dafa5fb3dcd56092949fc24 Mon Sep 17 00:00:00 2001 From: MagicCodingMan Date: Mon, 30 Nov 2026 16:22:06 -0500 Subject: [PATCH 5/5] Set the additive protected batch release to 4.1.0 --- Magic.IndexedDb.Cli/Magic.IndexedDb.Cli.csproj | 2 +- Magic.IndexedDb/Magic.IndexedDb.csproj | 4 ++-- docs/guides/managed-key-rotation.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Magic.IndexedDb.Cli/Magic.IndexedDb.Cli.csproj b/Magic.IndexedDb.Cli/Magic.IndexedDb.Cli.csproj index d29aac8..7be280d 100644 --- a/Magic.IndexedDb.Cli/Magic.IndexedDb.Cli.csproj +++ b/Magic.IndexedDb.Cli/Magic.IndexedDb.Cli.csproj @@ -7,7 +7,7 @@ true magicdb Magic.IndexedDb.Cli - 4.0.0 + 4.1.0 Magic Man Code-first, language-independent migration planning, validation, and static publishing for Magic IndexedDB. https://github.com/magiccodingman/Magic.IndexedDb diff --git a/Magic.IndexedDb/Magic.IndexedDb.csproj b/Magic.IndexedDb/Magic.IndexedDb.csproj index 45dd9ac..8462594 100644 --- a/Magic.IndexedDb/Magic.IndexedDb.csproj +++ b/Magic.IndexedDb/Magic.IndexedDb.csproj @@ -15,8 +15,8 @@ 4.0.0.0 README.md LICENSE.txt - 4.0.0.0 - 4.0.0 + 4.1.0.0 + 4.1.0 diff --git a/docs/guides/managed-key-rotation.md b/docs/guides/managed-key-rotation.md index 8d40028..5dec50c 100644 --- a/docs/guides/managed-key-rotation.md +++ b/docs/guides/managed-key-rotation.md @@ -144,7 +144,7 @@ the exporter and runtime agree on the persisted schema. ### Conditional batches across protected stores -Use `MagicProtectedBatch` for coordinated changes inside one unlocked, managed +Starting with Magic IndexedDB 4.1, use `MagicProtectedBatch` for coordinated changes inside one unlocked, managed database. Each entry addresses an exact primary key. Query filters and ordering do not participate. Guard-only entries use `ExpectAbsent` or `ExpectToken`. Insert implies an absence guard. Replace and delete require a token guard on the target.