@poolse/crypto 3.9.0 → 3.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/README.md +84 -0
- package/dist/index.cjs +464 -38
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +283 -1
- package/dist/index.d.ts +283 -1
- package/dist/index.js +442 -39
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -921,18 +921,18 @@ function purposeName(purpose) {
|
|
|
921
921
|
if (!name) throw new PoolseCryptoError("unsupported", `Unknown key-wrap purpose ${purpose}`);
|
|
922
922
|
return name;
|
|
923
923
|
}
|
|
924
|
-
async function wrapSymmetric(kek, purpose, key, keyVersion,
|
|
924
|
+
async function wrapSymmetric(kek, purpose, key, keyVersion, ad2) {
|
|
925
925
|
const name = purposeName(purpose);
|
|
926
926
|
const iv = randomBytes(IV_LENGTH);
|
|
927
927
|
const prefix = writeHeader(new ByteWriter(), Kind.KeyWrap, Alg.Aes256GcmHkdfSha256).u8(purpose).u32(keyVersion).bytes(await keyCheck(kek, `kek/${name}`)).bytes(iv).finish();
|
|
928
928
|
const aad = concat(
|
|
929
929
|
prefix,
|
|
930
|
-
encodeAssociatedData(`wrap/${name}`,
|
|
930
|
+
encodeAssociatedData(`wrap/${name}`, ad2, { "@keyVersion": keyVersion })
|
|
931
931
|
);
|
|
932
932
|
const ct = await aesEncrypt(await deriveAesKey(kek, `kek/${name}`), iv, key, aad);
|
|
933
933
|
return new ByteWriter().bytes(prefix).bytes16(ct).finish();
|
|
934
934
|
}
|
|
935
|
-
async function unwrapSymmetric(kek, purpose, wrap,
|
|
935
|
+
async function unwrapSymmetric(kek, purpose, wrap, ad2) {
|
|
936
936
|
const r = new ByteReader(wrap);
|
|
937
937
|
readHeader(r, Kind.KeyWrap, [Alg.Aes256GcmHkdfSha256]);
|
|
938
938
|
const got = r.u8();
|
|
@@ -952,7 +952,7 @@ async function unwrapSymmetric(kek, purpose, wrap, ad) {
|
|
|
952
952
|
await verifyKeyCheck(kek, `kek/${name}`, check);
|
|
953
953
|
const aad = concat(
|
|
954
954
|
prefix,
|
|
955
|
-
encodeAssociatedData(`wrap/${name}`,
|
|
955
|
+
encodeAssociatedData(`wrap/${name}`, ad2, { "@keyVersion": keyVersion })
|
|
956
956
|
);
|
|
957
957
|
const key = await aesDecrypt(await deriveAesKey(kek, `kek/${name}`), iv, ct, aad);
|
|
958
958
|
return { key, keyVersion };
|
|
@@ -960,10 +960,10 @@ async function unwrapSymmetric(kek, purpose, wrap, ad) {
|
|
|
960
960
|
async function kekFromShared(shared, ephemeral, recipient, name) {
|
|
961
961
|
return aesKey(await hkdf(shared, concat(ephemeral, recipient), label(DOMAIN, "pubwrap/", name)));
|
|
962
962
|
}
|
|
963
|
-
function signatureInput(body,
|
|
964
|
-
return concat(label(DOMAIN, "sig/pubwrap"), body,
|
|
963
|
+
function signatureInput(body, ad2) {
|
|
964
|
+
return concat(label(DOMAIN, "sig/pubwrap"), body, ad2);
|
|
965
965
|
}
|
|
966
|
-
async function wrapToDevice(recipient, purpose, key, keyVersion,
|
|
966
|
+
async function wrapToDevice(recipient, purpose, key, keyVersion, ad2, signer) {
|
|
967
967
|
const name = purposeName(purpose);
|
|
968
968
|
const recipientKey = await importP256Public("ecdh", recipient.encryption);
|
|
969
969
|
const ephemeral = await generateP256("ecdh");
|
|
@@ -973,7 +973,7 @@ async function wrapToDevice(recipient, purpose, key, keyVersion, ad, signer) {
|
|
|
973
973
|
const w = writeHeader(new ByteWriter(), Kind.PublicKeyWrap, Alg.P256).u8(purpose).u8(signer ? FLAG_SIGNED : 0).u32(keyVersion).bytes(deviceIdRaw(recipient)).bytes(ephemeralPublic);
|
|
974
974
|
if (signer) w.bytes(signer.publicKeys.signing);
|
|
975
975
|
const prefix = w.bytes(iv).finish();
|
|
976
|
-
const adBytes = encodeAssociatedData(`wrap/${name}`,
|
|
976
|
+
const adBytes = encodeAssociatedData(`wrap/${name}`, ad2, { "@keyVersion": keyVersion });
|
|
977
977
|
const kek = await kekFromShared(shared, ephemeralPublic, recipient.encryption, name);
|
|
978
978
|
const ct = await aesEncrypt(kek, iv, key, concat(prefix, adBytes));
|
|
979
979
|
const body = new ByteWriter().bytes(prefix).bytes16(ct).finish();
|
|
@@ -984,7 +984,7 @@ async function wrapToDevice(recipient, purpose, key, keyVersion, ad, signer) {
|
|
|
984
984
|
function asList(value) {
|
|
985
985
|
return Array.isArray(value) ? value : [value];
|
|
986
986
|
}
|
|
987
|
-
async function unwrapFromDevice(device, purpose, wrap,
|
|
987
|
+
async function unwrapFromDevice(device, purpose, wrap, ad2, requireSignatureFrom) {
|
|
988
988
|
const r = new ByteReader(wrap);
|
|
989
989
|
readHeader(r, Kind.PublicKeyWrap, [Alg.P256]);
|
|
990
990
|
const got = r.u8();
|
|
@@ -1012,7 +1012,7 @@ async function unwrapFromDevice(device, purpose, wrap, ad, requireSignatureFrom)
|
|
|
1012
1012
|
if (!constantTimeEqual(recipientId, deviceIdRaw(device.publicKeys))) {
|
|
1013
1013
|
throw new PoolseCryptoError("wrong-key", "This key was wrapped for a different device");
|
|
1014
1014
|
}
|
|
1015
|
-
const adBytes = encodeAssociatedData(`wrap/${name}`,
|
|
1015
|
+
const adBytes = encodeAssociatedData(`wrap/${name}`, ad2, { "@keyVersion": keyVersion });
|
|
1016
1016
|
let signer = null;
|
|
1017
1017
|
if (signingKey && signature) {
|
|
1018
1018
|
const verifier = await importP256Public("ecdsa", signingKey);
|
|
@@ -1144,17 +1144,17 @@ async function unwrapPreviousItemKey(wrap, current, options) {
|
|
|
1144
1144
|
}
|
|
1145
1145
|
|
|
1146
1146
|
// src/item.ts
|
|
1147
|
-
async function seal(key, type, plaintext,
|
|
1148
|
-
requireItemId(
|
|
1147
|
+
async function seal(key, type, plaintext, ad2) {
|
|
1148
|
+
requireItemId(ad2);
|
|
1149
1149
|
const raw = secretOf(key);
|
|
1150
1150
|
const iv = randomBytes(IV_LENGTH);
|
|
1151
1151
|
const prefix = writeHeader(new ByteWriter(), Kind.Item, Alg.Aes256GcmHkdfSha256).u32(key.version).bytes(await keyCheck(raw, "item")).bytes(iv).finish();
|
|
1152
|
-
const aad = concat(prefix, encodeAssociatedData("item",
|
|
1152
|
+
const aad = concat(prefix, encodeAssociatedData("item", ad2, { "@type": type }));
|
|
1153
1153
|
const ct = await aesEncrypt(await deriveAesKey(raw, "item-content"), iv, pad(plaintext), aad);
|
|
1154
1154
|
return concat(prefix, ct);
|
|
1155
1155
|
}
|
|
1156
|
-
async function open(key, type, envelope,
|
|
1157
|
-
requireItemId(
|
|
1156
|
+
async function open(key, type, envelope, ad2) {
|
|
1157
|
+
requireItemId(ad2);
|
|
1158
1158
|
const r = new ByteReader(envelope);
|
|
1159
1159
|
readHeader(r, Kind.Item, [Alg.Aes256GcmHkdfSha256]);
|
|
1160
1160
|
const keyVersion = r.u32();
|
|
@@ -1170,21 +1170,21 @@ async function open(key, type, envelope, ad) {
|
|
|
1170
1170
|
}
|
|
1171
1171
|
const raw = secretOf(key);
|
|
1172
1172
|
await verifyKeyCheck(raw, "item", check);
|
|
1173
|
-
const aad = concat(prefix, encodeAssociatedData("item",
|
|
1173
|
+
const aad = concat(prefix, encodeAssociatedData("item", ad2, { "@type": type }));
|
|
1174
1174
|
return unpad(await aesDecrypt(await deriveAesKey(raw, "item-content"), iv, ct, aad));
|
|
1175
1175
|
}
|
|
1176
|
-
function requireItemId(
|
|
1177
|
-
if (typeof
|
|
1176
|
+
function requireItemId(ad2) {
|
|
1177
|
+
if (typeof ad2.itemId !== "string" || ad2.itemId.length === 0) {
|
|
1178
1178
|
throw new PoolseCryptoError("malformed", "Associated data needs an itemId");
|
|
1179
1179
|
}
|
|
1180
1180
|
}
|
|
1181
|
-
async function encryptItem(key, content,
|
|
1181
|
+
async function encryptItem(key, content, ad2) {
|
|
1182
1182
|
if (typeof content.title !== "string")
|
|
1183
1183
|
throw new PoolseCryptoError("malformed", "title must be a string");
|
|
1184
|
-
return seal(key, "item", utf8(JSON.stringify(content)),
|
|
1184
|
+
return seal(key, "item", utf8(JSON.stringify(content)), ad2);
|
|
1185
1185
|
}
|
|
1186
|
-
async function decryptItem(key, envelope,
|
|
1187
|
-
const text = fromUtf8(await open(key, "item", envelope,
|
|
1186
|
+
async function decryptItem(key, envelope, ad2) {
|
|
1187
|
+
const text = fromUtf8(await open(key, "item", envelope, ad2));
|
|
1188
1188
|
let value;
|
|
1189
1189
|
try {
|
|
1190
1190
|
value = JSON.parse(text);
|
|
@@ -1196,11 +1196,11 @@ async function decryptItem(key, envelope, ad) {
|
|
|
1196
1196
|
}
|
|
1197
1197
|
return value;
|
|
1198
1198
|
}
|
|
1199
|
-
async function encryptBytes(key, plaintext,
|
|
1200
|
-
return seal(key, "bytes", plaintext,
|
|
1199
|
+
async function encryptBytes(key, plaintext, ad2) {
|
|
1200
|
+
return seal(key, "bytes", plaintext, ad2);
|
|
1201
1201
|
}
|
|
1202
|
-
async function decryptBytes(key, envelope,
|
|
1203
|
-
return open(key, "bytes", envelope,
|
|
1202
|
+
async function decryptBytes(key, envelope, ad2) {
|
|
1203
|
+
return open(key, "bytes", envelope, ad2);
|
|
1204
1204
|
}
|
|
1205
1205
|
|
|
1206
1206
|
// src/attachment.ts
|
|
@@ -1284,20 +1284,20 @@ function checkChunkSize(size) {
|
|
|
1284
1284
|
);
|
|
1285
1285
|
}
|
|
1286
1286
|
}
|
|
1287
|
-
function requireIds(
|
|
1288
|
-
if (!
|
|
1287
|
+
function requireIds(ad2) {
|
|
1288
|
+
if (!ad2.itemId || !ad2.attachmentId) {
|
|
1289
1289
|
throw new PoolseCryptoError("malformed", "Associated data needs itemId and attachmentId");
|
|
1290
1290
|
}
|
|
1291
1291
|
}
|
|
1292
|
-
async function* encryptAttachment(key, source,
|
|
1293
|
-
requireIds(
|
|
1292
|
+
async function* encryptAttachment(key, source, ad2, options = {}) {
|
|
1293
|
+
requireIds(ad2);
|
|
1294
1294
|
const chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE;
|
|
1295
1295
|
checkChunkSize(chunkSize);
|
|
1296
1296
|
const raw = secretOf(key);
|
|
1297
1297
|
const salt = randomBytes(SALT_LENGTH);
|
|
1298
1298
|
const header = writeHeader(new ByteWriter(), Kind.Attachment, Alg.Aes256GcmHkdfSha256).u32(key.version).bytes(await keyCheck(raw, "attachment")).bytes(salt).u32(chunkSize).finish();
|
|
1299
1299
|
const fileKey = await deriveAesKey(raw, "attachment", salt);
|
|
1300
|
-
const aad = concat(header, encodeAssociatedData("attachment",
|
|
1300
|
+
const aad = concat(header, encodeAssociatedData("attachment", ad2));
|
|
1301
1301
|
yield header;
|
|
1302
1302
|
const chunker = new Chunker();
|
|
1303
1303
|
let index = 0;
|
|
@@ -1309,8 +1309,8 @@ async function* encryptAttachment(key, source, ad, options = {}) {
|
|
|
1309
1309
|
}
|
|
1310
1310
|
yield await aesEncrypt(fileKey, nonce(index, true), chunker.takeAll(), aad);
|
|
1311
1311
|
}
|
|
1312
|
-
async function* decryptAttachment(key, source,
|
|
1313
|
-
requireIds(
|
|
1312
|
+
async function* decryptAttachment(key, source, ad2) {
|
|
1313
|
+
requireIds(ad2);
|
|
1314
1314
|
const input = new Chunker();
|
|
1315
1315
|
const it = iterate(source)[Symbol.asyncIterator]();
|
|
1316
1316
|
let ended = false;
|
|
@@ -1342,7 +1342,7 @@ async function* decryptAttachment(key, source, ad) {
|
|
|
1342
1342
|
const raw = secretOf(key);
|
|
1343
1343
|
await verifyKeyCheck(raw, "attachment", check);
|
|
1344
1344
|
const fileKey = await deriveAesKey(raw, "attachment", salt);
|
|
1345
|
-
const aad = concat(header, encodeAssociatedData("attachment",
|
|
1345
|
+
const aad = concat(header, encodeAssociatedData("attachment", ad2));
|
|
1346
1346
|
const sealed = chunkSize + TAG_LENGTH;
|
|
1347
1347
|
let index = 0;
|
|
1348
1348
|
for (; ; ) {
|
|
@@ -1362,11 +1362,11 @@ async function collect(stream) {
|
|
|
1362
1362
|
for await (const part of stream) parts.push(part);
|
|
1363
1363
|
return concat(...parts);
|
|
1364
1364
|
}
|
|
1365
|
-
async function encryptAttachmentBytes(key, source,
|
|
1366
|
-
return collect(encryptAttachment(key, source,
|
|
1365
|
+
async function encryptAttachmentBytes(key, source, ad2, options = {}) {
|
|
1366
|
+
return collect(encryptAttachment(key, source, ad2, options));
|
|
1367
1367
|
}
|
|
1368
|
-
async function decryptAttachmentBytes(key, source,
|
|
1369
|
-
return collect(decryptAttachment(key, source,
|
|
1368
|
+
async function decryptAttachmentBytes(key, source, ad2) {
|
|
1369
|
+
return collect(decryptAttachment(key, source, ad2));
|
|
1370
1370
|
}
|
|
1371
1371
|
function encryptedAttachmentSize(plainSize, chunkSize = DEFAULT_CHUNK_SIZE) {
|
|
1372
1372
|
checkChunkSize(chunkSize);
|
|
@@ -2081,6 +2081,409 @@ function createHttpBlobTransport(options) {
|
|
|
2081
2081
|
};
|
|
2082
2082
|
}
|
|
2083
2083
|
|
|
2084
|
+
// src/notes.ts
|
|
2085
|
+
function noteAssociatedData(noteId, revision, slot) {
|
|
2086
|
+
return { itemId: noteId, version: revision, slot };
|
|
2087
|
+
}
|
|
2088
|
+
function noteAttachmentAssociatedData(noteId, attachmentId) {
|
|
2089
|
+
return { itemId: noteId, attachmentId };
|
|
2090
|
+
}
|
|
2091
|
+
function folderAssociatedData(folderId) {
|
|
2092
|
+
return { itemId: folderId, slot: "folder" };
|
|
2093
|
+
}
|
|
2094
|
+
async function sealNote(key, note, options) {
|
|
2095
|
+
checkRevision(options.revision);
|
|
2096
|
+
const meta = { title: note.title, body: null, metadata: note.metadata ?? {} };
|
|
2097
|
+
return {
|
|
2098
|
+
meta: toBase64Url(
|
|
2099
|
+
await encryptItem(key, meta, noteAssociatedData(options.noteId, options.revision, "meta"))
|
|
2100
|
+
),
|
|
2101
|
+
content: toBase64Url(
|
|
2102
|
+
await encryptItem(
|
|
2103
|
+
key,
|
|
2104
|
+
{ title: note.title, body: note.body, metadata: note.metadata ?? {} },
|
|
2105
|
+
noteAssociatedData(options.noteId, options.revision, "content")
|
|
2106
|
+
)
|
|
2107
|
+
),
|
|
2108
|
+
key_version: key.version
|
|
2109
|
+
};
|
|
2110
|
+
}
|
|
2111
|
+
async function openNoteMeta(key, meta, options) {
|
|
2112
|
+
const m = await decryptItem(
|
|
2113
|
+
key,
|
|
2114
|
+
fromBase64Url(meta),
|
|
2115
|
+
noteAssociatedData(options.noteId, options.revision, "meta")
|
|
2116
|
+
);
|
|
2117
|
+
return { title: m.title, metadata: m.metadata ?? {} };
|
|
2118
|
+
}
|
|
2119
|
+
async function openNoteContent(key, content, options) {
|
|
2120
|
+
return decryptItem(
|
|
2121
|
+
key,
|
|
2122
|
+
fromBase64Url(content),
|
|
2123
|
+
noteAssociatedData(options.noteId, options.revision, "content")
|
|
2124
|
+
);
|
|
2125
|
+
}
|
|
2126
|
+
function envelopeKeyVersion(envelope) {
|
|
2127
|
+
const info = inspectEnvelope(fromBase64Url(envelope));
|
|
2128
|
+
if (info.keyVersion === void 0) {
|
|
2129
|
+
throw new PoolseCryptoError("malformed", "Not an item envelope");
|
|
2130
|
+
}
|
|
2131
|
+
return info.keyVersion;
|
|
2132
|
+
}
|
|
2133
|
+
async function noteKeyForVersion(current, keyHistory, version, options) {
|
|
2134
|
+
if (version > current.version) {
|
|
2135
|
+
throw new PoolseCryptoError("wrong-key", `Key version ${version} is newer than the note's`);
|
|
2136
|
+
}
|
|
2137
|
+
let key = current;
|
|
2138
|
+
while (key.version > version) {
|
|
2139
|
+
const wrap = keyHistory[String(key.version - 1)];
|
|
2140
|
+
if (!wrap) {
|
|
2141
|
+
throw new PoolseCryptoError("wrong-key", `key_history has no key ${key.version - 1}`);
|
|
2142
|
+
}
|
|
2143
|
+
key = await unwrapPreviousItemKey(fromBase64Url(wrap), key, { itemId: options.noteId });
|
|
2144
|
+
}
|
|
2145
|
+
return key;
|
|
2146
|
+
}
|
|
2147
|
+
async function sealFolder(name, accountKey, options) {
|
|
2148
|
+
const key = options.key ?? ItemKey.generate();
|
|
2149
|
+
return {
|
|
2150
|
+
key,
|
|
2151
|
+
name_envelope: toBase64Url(
|
|
2152
|
+
await encryptItem(key, { title: name, body: null }, folderAssociatedData(options.folderId))
|
|
2153
|
+
),
|
|
2154
|
+
key_wrap: toBase64Url(await wrapItemKey(key, accountKey, { itemId: options.folderId }))
|
|
2155
|
+
};
|
|
2156
|
+
}
|
|
2157
|
+
async function openFolderName(key, nameEnvelope, options) {
|
|
2158
|
+
const item = await decryptItem(
|
|
2159
|
+
key,
|
|
2160
|
+
fromBase64Url(nameEnvelope),
|
|
2161
|
+
folderAssociatedData(options.folderId)
|
|
2162
|
+
);
|
|
2163
|
+
return item.title;
|
|
2164
|
+
}
|
|
2165
|
+
async function shareWrapsFor(key, recipients, options) {
|
|
2166
|
+
const out = [];
|
|
2167
|
+
for (const r of recipients) {
|
|
2168
|
+
for (const device of r.devices) {
|
|
2169
|
+
const wrap = await shareItemKey(key, device, {
|
|
2170
|
+
itemId: options.noteId,
|
|
2171
|
+
signer: options.signer
|
|
2172
|
+
});
|
|
2173
|
+
out.push({ member_id: r.memberId, device_id: device.id, wrap: toBase64Url(wrap) });
|
|
2174
|
+
}
|
|
2175
|
+
}
|
|
2176
|
+
return out;
|
|
2177
|
+
}
|
|
2178
|
+
async function rotateNoteKey(previous, note, options) {
|
|
2179
|
+
const key = rotateItemKey(previous);
|
|
2180
|
+
const sealed = await sealNote(key, note, options);
|
|
2181
|
+
return {
|
|
2182
|
+
...sealed,
|
|
2183
|
+
key,
|
|
2184
|
+
key_wrap: toBase64Url(await wrapItemKey(key, options.accountKey, { itemId: options.noteId })),
|
|
2185
|
+
key_history: {
|
|
2186
|
+
[String(previous.version)]: toBase64Url(
|
|
2187
|
+
await wrapPreviousItemKey(previous, key, { itemId: options.noteId })
|
|
2188
|
+
)
|
|
2189
|
+
},
|
|
2190
|
+
share_wraps: await shareWrapsFor(key, options.remaining, options)
|
|
2191
|
+
};
|
|
2192
|
+
}
|
|
2193
|
+
function shareExpired(expiresAt, now = Date.now()) {
|
|
2194
|
+
if (!expiresAt) return false;
|
|
2195
|
+
const t = Date.parse(expiresAt);
|
|
2196
|
+
return Number.isFinite(t) && t <= now;
|
|
2197
|
+
}
|
|
2198
|
+
var RECOVERY_AUTH_LABEL = "recovery-auth";
|
|
2199
|
+
async function recoveryAuth(recoveryKey) {
|
|
2200
|
+
return hkdf(secretOf(recoveryKey), new Uint8Array(0), label(DOMAIN, RECOVERY_AUTH_LABEL), 32);
|
|
2201
|
+
}
|
|
2202
|
+
async function signForServer(device, message) {
|
|
2203
|
+
return ecdsaSign(devicePrivate(device).signing, message);
|
|
2204
|
+
}
|
|
2205
|
+
var SEP = new Uint8Array([0]);
|
|
2206
|
+
async function deviceApprovalMessage(memberId, newDeviceId, grant) {
|
|
2207
|
+
return concat(
|
|
2208
|
+
utf8("poolse-notes/v1/approve"),
|
|
2209
|
+
SEP,
|
|
2210
|
+
utf8(memberId),
|
|
2211
|
+
SEP,
|
|
2212
|
+
utf8(newDeviceId),
|
|
2213
|
+
SEP,
|
|
2214
|
+
await sha256(grant)
|
|
2215
|
+
);
|
|
2216
|
+
}
|
|
2217
|
+
async function recoveryReplaceMessage(memberId, keyId2, wrap, auth) {
|
|
2218
|
+
return concat(
|
|
2219
|
+
utf8("poolse-notes/v1/recovery"),
|
|
2220
|
+
SEP,
|
|
2221
|
+
utf8(memberId),
|
|
2222
|
+
SEP,
|
|
2223
|
+
utf8(keyId2),
|
|
2224
|
+
SEP,
|
|
2225
|
+
await sha256(wrap),
|
|
2226
|
+
await sha256(auth)
|
|
2227
|
+
);
|
|
2228
|
+
}
|
|
2229
|
+
async function signedDeviceGrant(grant, options) {
|
|
2230
|
+
const msg = await deviceApprovalMessage(options.memberId, options.newDeviceId, grant);
|
|
2231
|
+
return {
|
|
2232
|
+
grant: toBase64Url(grant),
|
|
2233
|
+
approver_device_id: options.approver.id,
|
|
2234
|
+
signature: toBase64Url(await signForServer(options.approver, msg))
|
|
2235
|
+
};
|
|
2236
|
+
}
|
|
2237
|
+
function noteAsDocument(note, toMarkdown) {
|
|
2238
|
+
const body = typeof note.body === "string" ? note.body : note.body === null ? "" : toMarkdown ? toMarkdown(note.body) : (() => {
|
|
2239
|
+
throw new PoolseCryptoError("malformed", "Pass toMarkdown for a structured body");
|
|
2240
|
+
})();
|
|
2241
|
+
const title = note.title.trim() || "Untitled note";
|
|
2242
|
+
return { title, markdown: `# ${title}
|
|
2243
|
+
|
|
2244
|
+
${body}`.trimEnd() + "\n" };
|
|
2245
|
+
}
|
|
2246
|
+
function checkRevision(revision) {
|
|
2247
|
+
if (!Number.isInteger(revision) || revision < 1) {
|
|
2248
|
+
throw new PoolseCryptoError("malformed", "revision is the revision the write creates (\u2265 1)");
|
|
2249
|
+
}
|
|
2250
|
+
}
|
|
2251
|
+
|
|
2252
|
+
// src/search.ts
|
|
2253
|
+
var MAX_WORD = 40;
|
|
2254
|
+
var MAX_WORDS_PER_NOTE = 5e3;
|
|
2255
|
+
function searchWords(text) {
|
|
2256
|
+
const norm = text.normalize("NFKD").replace(/\p{M}+/gu, "").toLowerCase();
|
|
2257
|
+
const out = [];
|
|
2258
|
+
for (const m of norm.matchAll(/[\p{L}\p{N}]+/gu)) out.push(m[0].slice(0, MAX_WORD));
|
|
2259
|
+
return out;
|
|
2260
|
+
}
|
|
2261
|
+
var NoteSearchIndex = class _NoteSearchIndex {
|
|
2262
|
+
#docs = /* @__PURE__ */ new Map();
|
|
2263
|
+
/** Notes in the index. */
|
|
2264
|
+
get size() {
|
|
2265
|
+
return this.#docs.size;
|
|
2266
|
+
}
|
|
2267
|
+
/** Add or replace a note. */
|
|
2268
|
+
put(id, doc) {
|
|
2269
|
+
const t = unique(searchWords(doc.title));
|
|
2270
|
+
const w = unique([...t, ...searchWords(doc.text)]).slice(0, MAX_WORDS_PER_NOTE);
|
|
2271
|
+
const u = typeof doc.updatedAt === "number" ? doc.updatedAt : doc.updatedAt ? Date.parse(doc.updatedAt) || 0 : 0;
|
|
2272
|
+
this.#docs.set(id, { t, w, u });
|
|
2273
|
+
}
|
|
2274
|
+
remove(id) {
|
|
2275
|
+
this.#docs.delete(id);
|
|
2276
|
+
}
|
|
2277
|
+
has(id) {
|
|
2278
|
+
return this.#docs.has(id);
|
|
2279
|
+
}
|
|
2280
|
+
clear() {
|
|
2281
|
+
this.#docs.clear();
|
|
2282
|
+
}
|
|
2283
|
+
/** Note ids matching every word of `query`, best first. Empty query → nothing. */
|
|
2284
|
+
search(query, limit = 50) {
|
|
2285
|
+
const words = unique(searchWords(query));
|
|
2286
|
+
if (words.length === 0) return [];
|
|
2287
|
+
const hits = [];
|
|
2288
|
+
for (const [id, doc] of this.#docs) {
|
|
2289
|
+
let score = 0;
|
|
2290
|
+
let all = true;
|
|
2291
|
+
for (const q of words) {
|
|
2292
|
+
let best = 0;
|
|
2293
|
+
for (const w of doc.w) {
|
|
2294
|
+
if (w === q) {
|
|
2295
|
+
best = 2;
|
|
2296
|
+
break;
|
|
2297
|
+
}
|
|
2298
|
+
if (w.startsWith(q)) best = 1;
|
|
2299
|
+
}
|
|
2300
|
+
if (best === 0) {
|
|
2301
|
+
all = false;
|
|
2302
|
+
break;
|
|
2303
|
+
}
|
|
2304
|
+
score += best;
|
|
2305
|
+
if (doc.t.some((w) => w.startsWith(q))) score += 3;
|
|
2306
|
+
}
|
|
2307
|
+
if (all) hits.push({ id, score, u: doc.u });
|
|
2308
|
+
}
|
|
2309
|
+
hits.sort((a, b) => b.score - a.score || b.u - a.u || a.id.localeCompare(b.id));
|
|
2310
|
+
return hits.slice(0, limit).map(({ id, score }) => ({ id, score }));
|
|
2311
|
+
}
|
|
2312
|
+
/** The index encrypted for this device's storage. `name` keeps several indexes apart. */
|
|
2313
|
+
async seal(accountKey, name = "notes") {
|
|
2314
|
+
const docs = {};
|
|
2315
|
+
for (const [id, d] of this.#docs) docs[id] = d;
|
|
2316
|
+
const key = await indexKey(accountKey);
|
|
2317
|
+
return encryptBytes(key, utf8(JSON.stringify({ v: 1, docs })), ad(name));
|
|
2318
|
+
}
|
|
2319
|
+
static async open(sealed, accountKey, name = "notes") {
|
|
2320
|
+
const key = await indexKey(accountKey);
|
|
2321
|
+
const raw = fromUtf8(await decryptBytes(key, sealed, ad(name)));
|
|
2322
|
+
let parsed;
|
|
2323
|
+
try {
|
|
2324
|
+
parsed = JSON.parse(raw);
|
|
2325
|
+
} catch {
|
|
2326
|
+
throw new PoolseCryptoError("malformed", "Search index is not JSON");
|
|
2327
|
+
}
|
|
2328
|
+
const p = parsed;
|
|
2329
|
+
if (p.v !== 1 || !p.docs || typeof p.docs !== "object") {
|
|
2330
|
+
throw new PoolseCryptoError("unsupported", "Unknown search index version");
|
|
2331
|
+
}
|
|
2332
|
+
const index = new _NoteSearchIndex();
|
|
2333
|
+
for (const [id, d] of Object.entries(p.docs)) {
|
|
2334
|
+
if (Array.isArray(d.t) && Array.isArray(d.w)) {
|
|
2335
|
+
index.#docs.set(id, { t: d.t, w: d.w, u: typeof d.u === "number" ? d.u : 0 });
|
|
2336
|
+
}
|
|
2337
|
+
}
|
|
2338
|
+
return index;
|
|
2339
|
+
}
|
|
2340
|
+
};
|
|
2341
|
+
function ad(name) {
|
|
2342
|
+
return { itemId: "search-index", slot: name };
|
|
2343
|
+
}
|
|
2344
|
+
async function indexKey(accountKey) {
|
|
2345
|
+
const raw = await hkdf(
|
|
2346
|
+
secretOf(accountKey),
|
|
2347
|
+
new Uint8Array(0),
|
|
2348
|
+
label(DOMAIN, "key/search-index")
|
|
2349
|
+
);
|
|
2350
|
+
return ItemKey.fromBytes(raw, 1);
|
|
2351
|
+
}
|
|
2352
|
+
function unique(words) {
|
|
2353
|
+
return [...new Set(words)];
|
|
2354
|
+
}
|
|
2355
|
+
|
|
2356
|
+
// src/outbox.ts
|
|
2357
|
+
var NoteOutbox = class _NoteOutbox {
|
|
2358
|
+
#entries;
|
|
2359
|
+
#storage;
|
|
2360
|
+
#key;
|
|
2361
|
+
#flushing = null;
|
|
2362
|
+
constructor(entries, storage, key) {
|
|
2363
|
+
this.#entries = entries;
|
|
2364
|
+
this.#storage = storage;
|
|
2365
|
+
this.#key = key;
|
|
2366
|
+
}
|
|
2367
|
+
static async load(options) {
|
|
2368
|
+
const key = await outboxKey(options.accountKey);
|
|
2369
|
+
const sealed = await options.storage.read();
|
|
2370
|
+
let entries = [];
|
|
2371
|
+
if (sealed && sealed.length > 0) {
|
|
2372
|
+
const text = fromUtf8(await decryptBytes(key, sealed, AD));
|
|
2373
|
+
const parsed = JSON.parse(text);
|
|
2374
|
+
if (parsed.v !== 1 || !Array.isArray(parsed.entries)) {
|
|
2375
|
+
throw new PoolseCryptoError("unsupported", "Unknown outbox version");
|
|
2376
|
+
}
|
|
2377
|
+
entries = parsed.entries;
|
|
2378
|
+
}
|
|
2379
|
+
return new _NoteOutbox(entries, options.storage, key);
|
|
2380
|
+
}
|
|
2381
|
+
/** Waiting writes, oldest first. */
|
|
2382
|
+
get entries() {
|
|
2383
|
+
return this.#entries;
|
|
2384
|
+
}
|
|
2385
|
+
/** Whether a note has unsent edits (show "Not synced yet"). */
|
|
2386
|
+
isPending(noteId) {
|
|
2387
|
+
return this.#entries.some((e) => e.noteId === noteId);
|
|
2388
|
+
}
|
|
2389
|
+
/** Queue an edit (or a new note, `baseRevision` 0). Replaces an earlier queued edit of the note. */
|
|
2390
|
+
async put(noteId, baseRevision, data) {
|
|
2391
|
+
this.#enqueue(noteId, "put", baseRevision, data);
|
|
2392
|
+
await this.#save();
|
|
2393
|
+
}
|
|
2394
|
+
/** Queue a delete. A note made offline and never sent is just forgotten. */
|
|
2395
|
+
async delete(noteId, baseRevision) {
|
|
2396
|
+
const prior = this.#entries.find((e) => e.noteId === noteId);
|
|
2397
|
+
if (prior && prior.baseRevision === 0) {
|
|
2398
|
+
this.#entries = this.#entries.filter((e) => e.noteId !== noteId);
|
|
2399
|
+
} else {
|
|
2400
|
+
this.#enqueue(noteId, "delete", baseRevision, null);
|
|
2401
|
+
}
|
|
2402
|
+
await this.#save();
|
|
2403
|
+
}
|
|
2404
|
+
/** Send everything, in order. Concurrent calls share one run. */
|
|
2405
|
+
flush(options) {
|
|
2406
|
+
this.#flushing ??= this.#flush(options).finally(() => {
|
|
2407
|
+
this.#flushing = null;
|
|
2408
|
+
});
|
|
2409
|
+
return this.#flushing;
|
|
2410
|
+
}
|
|
2411
|
+
async #flush(options) {
|
|
2412
|
+
const result = { written: [], dropped: [], pending: 0 };
|
|
2413
|
+
const maxConflicts = options.maxConflicts ?? 3;
|
|
2414
|
+
while (this.#entries.length > 0) {
|
|
2415
|
+
const entry = this.#entries[0];
|
|
2416
|
+
let conflicts = 0;
|
|
2417
|
+
let current = entry;
|
|
2418
|
+
let done = false;
|
|
2419
|
+
while (!done) {
|
|
2420
|
+
let res;
|
|
2421
|
+
try {
|
|
2422
|
+
res = await options.send(current);
|
|
2423
|
+
} catch (error) {
|
|
2424
|
+
current.attempts += 1;
|
|
2425
|
+
await this.#save();
|
|
2426
|
+
result.pending = this.#entries.length;
|
|
2427
|
+
result.error = error;
|
|
2428
|
+
return result;
|
|
2429
|
+
}
|
|
2430
|
+
if (res.status === "ok") {
|
|
2431
|
+
result.written.push(current.noteId);
|
|
2432
|
+
options.onWritten?.(current.noteId, res.revision);
|
|
2433
|
+
done = true;
|
|
2434
|
+
} else if (res.status === "gone") {
|
|
2435
|
+
result.dropped.push(current.noteId);
|
|
2436
|
+
done = true;
|
|
2437
|
+
} else {
|
|
2438
|
+
conflicts += 1;
|
|
2439
|
+
const merged = current.op === "delete" ? null : options.resolve ? await options.resolve(current.data, res.current, current) : current.data;
|
|
2440
|
+
if (conflicts > maxConflicts || current.op === "put" && merged === null) {
|
|
2441
|
+
result.dropped.push(current.noteId);
|
|
2442
|
+
done = true;
|
|
2443
|
+
} else {
|
|
2444
|
+
current = { ...current, baseRevision: res.revision, data: merged };
|
|
2445
|
+
this.#entries[0] = current;
|
|
2446
|
+
}
|
|
2447
|
+
}
|
|
2448
|
+
}
|
|
2449
|
+
this.#entries.shift();
|
|
2450
|
+
await this.#save();
|
|
2451
|
+
}
|
|
2452
|
+
return result;
|
|
2453
|
+
}
|
|
2454
|
+
#enqueue(noteId, op, baseRevision, data) {
|
|
2455
|
+
const i = this.#entries.findIndex((e) => e.noteId === noteId);
|
|
2456
|
+
if (i !== -1) {
|
|
2457
|
+
const prior = this.#entries[i];
|
|
2458
|
+
this.#entries[i] = { ...prior, op, data, queuedAt: Date.now() };
|
|
2459
|
+
return;
|
|
2460
|
+
}
|
|
2461
|
+
this.#entries.push({ noteId, op, baseRevision, data, queuedAt: Date.now(), attempts: 0 });
|
|
2462
|
+
}
|
|
2463
|
+
async #save() {
|
|
2464
|
+
const text = JSON.stringify({ v: 1, entries: this.#entries });
|
|
2465
|
+
await this.#storage.write(await encryptBytes(this.#key, utf8(text), AD));
|
|
2466
|
+
}
|
|
2467
|
+
};
|
|
2468
|
+
var AD = { itemId: "notes-outbox" };
|
|
2469
|
+
async function outboxKey(accountKey) {
|
|
2470
|
+
const raw = await hkdf(
|
|
2471
|
+
secretOf(accountKey),
|
|
2472
|
+
new Uint8Array(0),
|
|
2473
|
+
label(DOMAIN, "key/notes-outbox")
|
|
2474
|
+
);
|
|
2475
|
+
return ItemKey.fromBytes(raw, 1);
|
|
2476
|
+
}
|
|
2477
|
+
var MemoryOutboxStorage = class {
|
|
2478
|
+
data = null;
|
|
2479
|
+
async read() {
|
|
2480
|
+
return this.data;
|
|
2481
|
+
}
|
|
2482
|
+
async write(data) {
|
|
2483
|
+
this.data = data;
|
|
2484
|
+
}
|
|
2485
|
+
};
|
|
2486
|
+
|
|
2084
2487
|
exports.ATTACHMENT_HEADER_LENGTH = ATTACHMENT_HEADER_LENGTH;
|
|
2085
2488
|
exports.AccountKey = AccountKey;
|
|
2086
2489
|
exports.Alg = Alg;
|
|
@@ -2096,6 +2499,9 @@ exports.Kind = Kind;
|
|
|
2096
2499
|
exports.MAX_CHUNK_SIZE = MAX_CHUNK_SIZE;
|
|
2097
2500
|
exports.MIN_CHUNK_SIZE = MIN_CHUNK_SIZE;
|
|
2098
2501
|
exports.MemoryBlobTransport = MemoryBlobTransport;
|
|
2502
|
+
exports.MemoryOutboxStorage = MemoryOutboxStorage;
|
|
2503
|
+
exports.NoteOutbox = NoteOutbox;
|
|
2504
|
+
exports.NoteSearchIndex = NoteSearchIndex;
|
|
2099
2505
|
exports.PoolseCryptoError = PoolseCryptoError;
|
|
2100
2506
|
exports.RecoveryKey = RecoveryKey;
|
|
2101
2507
|
exports.WrapPurpose = WrapPurpose;
|
|
@@ -2110,6 +2516,7 @@ exports.decryptAttachment = decryptAttachment;
|
|
|
2110
2516
|
exports.decryptAttachmentBytes = decryptAttachmentBytes;
|
|
2111
2517
|
exports.decryptBytes = decryptBytes;
|
|
2112
2518
|
exports.decryptItem = decryptItem;
|
|
2519
|
+
exports.deviceApprovalMessage = deviceApprovalMessage;
|
|
2113
2520
|
exports.deviceFingerprint = deviceFingerprint;
|
|
2114
2521
|
exports.devicePublicKeys = devicePublicKeys;
|
|
2115
2522
|
exports.encodeAssociatedData = encodeAssociatedData;
|
|
@@ -2119,20 +2526,39 @@ exports.encryptAttachmentBytes = encryptAttachmentBytes;
|
|
|
2119
2526
|
exports.encryptBytes = encryptBytes;
|
|
2120
2527
|
exports.encryptItem = encryptItem;
|
|
2121
2528
|
exports.encryptedAttachmentSize = encryptedAttachmentSize;
|
|
2529
|
+
exports.envelopeKeyVersion = envelopeKeyVersion;
|
|
2530
|
+
exports.folderAssociatedData = folderAssociatedData;
|
|
2122
2531
|
exports.fromBase32 = fromBase32;
|
|
2123
2532
|
exports.fromBase64Url = fromBase64Url;
|
|
2124
2533
|
exports.fromHex = fromHex;
|
|
2125
2534
|
exports.generateRecoveryKey = generateRecoveryKey;
|
|
2126
2535
|
exports.inspectEnvelope = inspectEnvelope;
|
|
2127
2536
|
exports.isValidBlobKey = isValidBlobKey;
|
|
2537
|
+
exports.noteAsDocument = noteAsDocument;
|
|
2538
|
+
exports.noteAssociatedData = noteAssociatedData;
|
|
2539
|
+
exports.noteAttachmentAssociatedData = noteAttachmentAssociatedData;
|
|
2540
|
+
exports.noteKeyForVersion = noteKeyForVersion;
|
|
2541
|
+
exports.openFolderName = openFolderName;
|
|
2542
|
+
exports.openNoteContent = openNoteContent;
|
|
2543
|
+
exports.openNoteMeta = openNoteMeta;
|
|
2128
2544
|
exports.openSharedItemKey = openSharedItemKey;
|
|
2129
2545
|
exports.padmeLength = padmeLength;
|
|
2130
2546
|
exports.parseRecoveryKey = parseRecoveryKey;
|
|
2131
2547
|
exports.readDeviceRequest = readDeviceRequest;
|
|
2548
|
+
exports.recoveryAuth = recoveryAuth;
|
|
2549
|
+
exports.recoveryReplaceMessage = recoveryReplaceMessage;
|
|
2132
2550
|
exports.rotateItemKey = rotateItemKey;
|
|
2551
|
+
exports.rotateNoteKey = rotateNoteKey;
|
|
2133
2552
|
exports.sameDevice = sameDevice;
|
|
2553
|
+
exports.sealFolder = sealFolder;
|
|
2554
|
+
exports.sealNote = sealNote;
|
|
2555
|
+
exports.searchWords = searchWords;
|
|
2556
|
+
exports.shareExpired = shareExpired;
|
|
2134
2557
|
exports.shareItemKey = shareItemKey;
|
|
2135
2558
|
exports.shareItemKeyWithDevices = shareItemKeyWithDevices;
|
|
2559
|
+
exports.shareWrapsFor = shareWrapsFor;
|
|
2560
|
+
exports.signForServer = signForServer;
|
|
2561
|
+
exports.signedDeviceGrant = signedDeviceGrant;
|
|
2136
2562
|
exports.toBase32 = toBase32;
|
|
2137
2563
|
exports.toBase64Url = toBase64Url;
|
|
2138
2564
|
exports.toHex = toHex;
|