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