@agora-sdk/secure-chat-core 0.3.0 → 0.5.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.
Files changed (67) hide show
  1. package/dist/cjs/backup/passphrase-strength.d.ts +22 -0
  2. package/dist/cjs/backup/passphrase-strength.js +75 -0
  3. package/dist/cjs/backup/passphrase-strength.js.map +1 -0
  4. package/dist/cjs/context/secure-chat-context.d.ts +12 -1
  5. package/dist/cjs/context/secure-chat-context.js +3 -1
  6. package/dist/cjs/context/secure-chat-context.js.map +1 -1
  7. package/dist/cjs/contract/index.d.ts +2 -150
  8. package/dist/cjs/contract/index.js +11 -10
  9. package/dist/cjs/contract/index.js.map +1 -1
  10. package/dist/cjs/hooks/useSecureBackup.d.ts +67 -0
  11. package/dist/cjs/hooks/useSecureBackup.js +207 -0
  12. package/dist/cjs/hooks/useSecureBackup.js.map +1 -0
  13. package/dist/cjs/hooks/useSecureDevice.d.ts +21 -1
  14. package/dist/cjs/hooks/useSecureDevice.js +46 -5
  15. package/dist/cjs/hooks/useSecureDevice.js.map +1 -1
  16. package/dist/cjs/hooks/useSecureMessages.d.ts +16 -3
  17. package/dist/cjs/hooks/useSecureMessages.js +38 -15
  18. package/dist/cjs/hooks/useSecureMessages.js.map +1 -1
  19. package/dist/cjs/hooks/useSecureSafetyNumber.d.ts +30 -0
  20. package/dist/cjs/hooks/useSecureSafetyNumber.js +82 -0
  21. package/dist/cjs/hooks/useSecureSafetyNumber.js.map +1 -0
  22. package/dist/cjs/index.d.ts +12 -1
  23. package/dist/cjs/index.js +16 -1
  24. package/dist/cjs/index.js.map +1 -1
  25. package/dist/cjs/transport/socket.d.ts +15 -3
  26. package/dist/cjs/transport/socket.js +4 -2
  27. package/dist/cjs/transport/socket.js.map +1 -1
  28. package/dist/cjs/util/padding.d.ts +39 -0
  29. package/dist/cjs/util/padding.js +80 -0
  30. package/dist/cjs/util/padding.js.map +1 -0
  31. package/dist/cjs/util/safety-number.d.ts +27 -0
  32. package/dist/cjs/util/safety-number.js +84 -0
  33. package/dist/cjs/util/safety-number.js.map +1 -0
  34. package/dist/esm/backup/passphrase-strength.d.ts +22 -0
  35. package/dist/esm/backup/passphrase-strength.js +72 -0
  36. package/dist/esm/backup/passphrase-strength.js.map +1 -0
  37. package/dist/esm/context/secure-chat-context.d.ts +12 -1
  38. package/dist/esm/context/secure-chat-context.js +3 -1
  39. package/dist/esm/context/secure-chat-context.js.map +1 -1
  40. package/dist/esm/contract/index.d.ts +2 -150
  41. package/dist/esm/contract/index.js +11 -10
  42. package/dist/esm/contract/index.js.map +1 -1
  43. package/dist/esm/hooks/useSecureBackup.d.ts +67 -0
  44. package/dist/esm/hooks/useSecureBackup.js +204 -0
  45. package/dist/esm/hooks/useSecureBackup.js.map +1 -0
  46. package/dist/esm/hooks/useSecureDevice.d.ts +21 -1
  47. package/dist/esm/hooks/useSecureDevice.js +46 -5
  48. package/dist/esm/hooks/useSecureDevice.js.map +1 -1
  49. package/dist/esm/hooks/useSecureMessages.d.ts +16 -3
  50. package/dist/esm/hooks/useSecureMessages.js +38 -15
  51. package/dist/esm/hooks/useSecureMessages.js.map +1 -1
  52. package/dist/esm/hooks/useSecureSafetyNumber.d.ts +30 -0
  53. package/dist/esm/hooks/useSecureSafetyNumber.js +79 -0
  54. package/dist/esm/hooks/useSecureSafetyNumber.js.map +1 -0
  55. package/dist/esm/index.d.ts +12 -1
  56. package/dist/esm/index.js +7 -0
  57. package/dist/esm/index.js.map +1 -1
  58. package/dist/esm/transport/socket.d.ts +15 -3
  59. package/dist/esm/transport/socket.js +4 -2
  60. package/dist/esm/transport/socket.js.map +1 -1
  61. package/dist/esm/util/padding.d.ts +39 -0
  62. package/dist/esm/util/padding.js +75 -0
  63. package/dist/esm/util/padding.js.map +1 -0
  64. package/dist/esm/util/safety-number.d.ts +27 -0
  65. package/dist/esm/util/safety-number.js +81 -0
  66. package/dist/esm/util/safety-number.js.map +1 -0
  67. package/package.json +3 -2
@@ -0,0 +1,22 @@
1
+ /** The outcome of {@link estimatePassphraseStrength}: a coarse 0–4 score plus display copy. */
2
+ export interface PassphraseStrength {
3
+ /** 0 (weakest) … 4 (strongest) — for a 5-segment meter. */
4
+ score: 0 | 1 | 2 | 3 | 4;
5
+ /** A short human label for the score (e.g. "Weak", "Strong"). */
6
+ label: string;
7
+ /** A specific reason the passphrase is weak, when applicable (e.g. a common password). */
8
+ warning?: string;
9
+ }
10
+ /**
11
+ * Estimate the strength of a backup passphrase for a strength meter.
12
+ *
13
+ * @param passphrase - The candidate passphrase (never logged or sent anywhere).
14
+ * @returns A {@link PassphraseStrength} with a 0–4 score, a label, and an optional warning.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * const { score, label, warning } = estimatePassphraseStrength(input);
19
+ * // render a 5-segment meter from `score`, show `warning` if present.
20
+ * ```
21
+ */
22
+ export declare function estimatePassphraseStrength(passphrase: string): PassphraseStrength;
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ // Passphrase-strength estimator for backup UX.
3
+ //
4
+ // Why this exists (CLAUDE.md #1 + spec §16.5): the blind server stores the passphrase-encrypted
5
+ // backup blob, so a weak passphrase is offline-brute-forceable on a DB exfil. The real argon2id KDF
6
+ // raises the cost per guess, but it can't rescue a guessable passphrase — so we nudge the user toward
7
+ // a strong one at entry time. This is a deliberately small, dependency-free heuristic (length +
8
+ // character-class diversity + a common-password penalty), NOT a substitute for zxcvbn-grade entropy
9
+ // estimation. It runs purely client-side and never logs or transmits the passphrase.
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.estimatePassphraseStrength = estimatePassphraseStrength;
12
+ const LABELS = ["Very weak", "Weak", "Fair", "Strong", "Very strong"];
13
+ // A tiny set of the most-guessed passwords/substrings. Not exhaustive — a guardrail against the
14
+ // obvious, not a real dictionary check.
15
+ const COMMON = [
16
+ "password", "passw0rd", "12345", "123456", "qwerty", "letmein", "admin", "welcome",
17
+ "iloveyou", "abc123", "hunter2", "monkey", "dragon", "trustno1", "secret",
18
+ ];
19
+ /**
20
+ * Estimate the strength of a backup passphrase for a strength meter.
21
+ *
22
+ * @param passphrase - The candidate passphrase (never logged or sent anywhere).
23
+ * @returns A {@link PassphraseStrength} with a 0–4 score, a label, and an optional warning.
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * const { score, label, warning } = estimatePassphraseStrength(input);
28
+ * // render a 5-segment meter from `score`, show `warning` if present.
29
+ * ```
30
+ */
31
+ function estimatePassphraseStrength(passphrase) {
32
+ const pw = passphrase ?? "";
33
+ if (pw.length === 0)
34
+ return { score: 0, label: LABELS[0] };
35
+ const lower = pw.toLowerCase();
36
+ const hitsCommon = COMMON.some((c) => lower.includes(c));
37
+ // Character-class diversity.
38
+ let classes = 0;
39
+ if (/[a-z]/.test(pw))
40
+ classes++;
41
+ if (/[A-Z]/.test(pw))
42
+ classes++;
43
+ if (/[0-9]/.test(pw))
44
+ classes++;
45
+ if (/[^a-zA-Z0-9]/.test(pw))
46
+ classes++;
47
+ // Length is the dominant factor (passphrases >> complex-but-short passwords).
48
+ let score = 0;
49
+ if (pw.length >= 8)
50
+ score++;
51
+ if (pw.length >= 12)
52
+ score++;
53
+ if (pw.length >= 16)
54
+ score++;
55
+ // Diversity adds at most one step, and only once there's some length.
56
+ if (classes >= 3 && pw.length >= 8)
57
+ score++;
58
+ // A short, single-class passphrase never rates above "weak".
59
+ if (pw.length < 8 || classes <= 1)
60
+ score = Math.min(score, 1);
61
+ // A recognizably common password is capped hard regardless of shape.
62
+ if (hitsCommon)
63
+ score = Math.min(score, 1);
64
+ const clamped = Math.max(0, Math.min(4, score));
65
+ return {
66
+ score: clamped,
67
+ label: LABELS[clamped],
68
+ warning: hitsCommon
69
+ ? "This looks like a common password — choose something less guessable."
70
+ : clamped <= 1
71
+ ? "Use a longer passphrase (4+ random words) with mixed character types."
72
+ : undefined,
73
+ };
74
+ }
75
+ //# sourceMappingURL=passphrase-strength.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"passphrase-strength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C;IAChC,IAAI,cAAc,CAAC,IAAI,CAAC,EAAE,CAAC;QAAE,OAAO,EAAE,CAAC;IAEvC,8EAA8E;IAC9E,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,IAAI,EAAE,CAAC,MAAM,IAAI,CAAC;QAAE,KAAK,EAAE,CAAC;IAC5B,IAAI,EAAE,CAAC,MAAM,IAAI,EAAE;QAAE,KAAK,EAAE,CAAC;IAC7B,IAAI,EAAE,CAAC,MAAM,IAAI,EAAE;QAAE,KAAK,EAAE,CAAC;IAC7B,sEAAsE;IACtE,IAAI,OAAO,IAAI,CAAC,IAAI,EAAE,CAAC,MAAM,IAAI,CAAC;QAAE,KAAK,EAAE,CAAC;IAE5C,6DAA6D;IAC7D,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,IAAI,CAAC;QAAE,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;IAE9D,qEAAqE;IACrE,IAAI,UAAU;QAAE,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;IAE3C,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAAgC,CAAC;IAC/E,OAAO;QACL,KAAK,EAAE,OAAO;QACd,KAAK,EAAE,MAAM,CAAC,OAAO,CAAC;QACtB,OAAO,EAAE,UAAU;YACjB,CAAC,CAAC,sEAAsE;YACxE,CAAC,CAAC,OAAO,IAAI,CAAC;gBACZ,CAAC,CAAC,uEAAuE;gBACzE,CAAC,CAAC,SAAS;KAChB,CAAC;AACJ,CAAC"}
@@ -4,6 +4,7 @@ import { SecureChatRestClient } from "../transport/rest.js";
4
4
  import { SecureChatSocketClient } from "../transport/socket.js";
5
5
  import { SecureChatStore } from "../persistence/store.js";
6
6
  import { SecureChatRepository } from "../persistence/repository.js";
7
+ import { PaddingPolicy } from "../util/padding.js";
7
8
  /**
8
9
  * The value exposed by {@link useSecureChat}: shared transport clients, the injected crypto, the
9
10
  * persistence repository, the group-handle resolver, and the active project id.
@@ -31,6 +32,11 @@ export interface SecureChatContextValue {
31
32
  * @returns An unsubscribe function.
32
33
  */
33
34
  subscribeGroupChange: (listener: () => void) => () => void;
35
+ /**
36
+ * Outbound message size-bucket padding policy. `useSecureMessages` pads plaintext to this before
37
+ * encryption so ciphertext size leaks less; defaults to `"ladder"`.
38
+ */
39
+ padding: PaddingPolicy;
34
40
  /** The Agora project id these clients are scoped to. */
35
41
  projectId: string;
36
42
  }
@@ -50,6 +56,11 @@ export interface SecureChatProviderProps {
50
56
  baseUrl?: string;
51
57
  /** Override the socket origin. Defaults to @agora-sdk/core `getSocketUrl()`. */
52
58
  socketUrl?: string;
59
+ /**
60
+ * Outbound message size-bucket padding policy (metadata hardening). `"ladder"` (default) pads each
61
+ * message up to a fixed size bucket so ciphertext length leaks less; `"none"` frames without padding.
62
+ */
63
+ padding?: PaddingPolicy;
53
64
  children: React.ReactNode;
54
65
  }
55
66
  /**
@@ -66,7 +77,7 @@ export interface SecureChatProviderProps {
66
77
  * </SecureChatProvider>
67
78
  * ```
68
79
  */
69
- export declare function SecureChatProvider({ crypto, projectId, store, accessToken, getAccessToken, baseUrl, socketUrl, children, }: SecureChatProviderProps): React.JSX.Element;
80
+ export declare function SecureChatProvider({ crypto, projectId, store, accessToken, getAccessToken, baseUrl, socketUrl, padding, children, }: SecureChatProviderProps): React.JSX.Element;
70
81
  /**
71
82
  * Access the nearest {@link SecureChatContextValue}.
72
83
  *
@@ -31,7 +31,7 @@ const SecureChatContext = (0, react_1.createContext)(null);
31
31
  * </SecureChatProvider>
32
32
  * ```
33
33
  */
34
- function SecureChatProvider({ crypto, projectId, store, accessToken, getAccessToken, baseUrl, socketUrl, children, }) {
34
+ function SecureChatProvider({ crypto, projectId, store, accessToken, getAccessToken, baseUrl, socketUrl, padding = "ladder", children, }) {
35
35
  const tokenRef = (0, react_1.useRef)(accessToken);
36
36
  tokenRef.current = accessToken;
37
37
  const resolveToken = (0, react_1.useMemo)(() => getAccessToken ?? (() => tokenRef.current), [getAccessToken]);
@@ -95,6 +95,7 @@ function SecureChatProvider({ crypto, projectId, store, accessToken, getAccessTo
95
95
  rememberGroup,
96
96
  getGroupVersion,
97
97
  subscribeGroupChange,
98
+ padding,
98
99
  projectId,
99
100
  }), [
100
101
  rest,
@@ -105,6 +106,7 @@ function SecureChatProvider({ crypto, projectId, store, accessToken, getAccessTo
105
106
  rememberGroup,
106
107
  getGroupVersion,
107
108
  subscribeGroupChange,
109
+ padding,
108
110
  projectId,
109
111
  ]);
110
112
  return (0, jsx_runtime_1.jsx)(SecureChatContext.Provider, { value: value, children: children });
@@ -1 +1 @@
1
- {"version":3,"file":"secure-chat-context.js","sourceRoot":"","sources":["../../../src/context/secure-chat-context.tsx"],"names":[],"mappings":";;AAoFA,gDAwHC;AAQD,sCAMC;;AA1ND,yFAAyF;AACzF,EAAE;AACF,gGAAgG;AAChG,kGAAkG;AAClG,+FAA+F;AAC/F,mGAAmG;AACnG,gEAAgE;AAEhE,iCAAkG;AAClG,0CAA8D;AAG9D,kDAA4D;AAC5D,sDAAgE;AAEhE,oEAA6D;AAC7D,gEAAoE;AAiCpE,MAAM,iBAAiB,GAAG,IAAA,qBAAa,EAAgC,IAAI,CAAC,CAAC;AAqB7E;;;;;;;;;;;;;GAaG;AACH,SAAgB,kBAAkB,CAAC,EACjC,MAAM,EACN,SAAS,EACT,KAAK,EACL,WAAW,EACX,cAAc,EACd,OAAO,EACP,SAAS,EACT,QAAQ,GACgB;IACxB,MAAM,QAAQ,GAAG,IAAA,cAAM,EAAqB,WAAW,CAAC,CAAC;IACzD,QAAQ,CAAC,OAAO,GAAG,WAAW,CAAC;IAE/B,MAAM,YAAY,GAAG,IAAA,eAAO,EAC1B,GAAG,EAAE,CAAC,cAAc,IAAI,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC,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AEF,MAAM,oBAAoB,GAAG,IAAA,mBAAW,EAAC,CAAC,QAAoB,EAAgB,EAAE;QAC9E,cAAc,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QACrC,OAAO,GAAG,EAAE;YACV,cAAc,CAAC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QAC1C,CAAC,CAAC;IACJ,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,IAAA,iBAAS,EAAC,GAAG,EAAE;QACb,OAAO,GAAG,EAAE,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;IACnC,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;IAEb,MAAM,KAAK,GAAG,IAAA,eAAO,EACnB,GAAG,EAAE,CAAC,CAAC;QACL,IAAI;QACJ,MAAM;QACN,MAAM;QACN,IAAI;QACJ,YAAY;QACZ,aAAa;QACb,eAAe;QACf,oBAAoB;QACpB,SAAS;KACV,CAAC,EACF;QACE,IAAI;QACJ,MAAM;QACN,MAAM;QACN,IAAI;QACJ,YAAY;QACZ,aAAa;QACb,eAAe;QACf,oBAAoB;QACpB,SAAS;KACV,CACF,CAAC;IAEF,OAAO,uBAAC,iBAAiB,CAAC,QAAQ,IAAC,KAAK,EAAE,KAAK,YAAG,QAAQ,GAA8B,CAAC;AAC3F,CAAC;AAED;;;;;GAKG;AACH,SAAgB,aAAa;IAC3B,MAAM,GAAG,GAAG,IAAA,kBAAU,EAAC,iBAAiB,CAAC,CAAC;IAC1C,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,MAAM,IAAI,KAAK,CAAC,2DAA2D,CAAC,CAAC;IAC/E,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC"}
1
+ {"version":3,"file":"secure-chat-context.js","sourceRoot":"","sources":["../../../src/context/secure-chat-context.tsx"],"names":[],"mappings":";;AA+FA,gDA2HC;AAQD,sCAMC;;AAxOD,yFAAyF;AACzF,EAAE;AACF,gGAAgG;AAChG,kGAAkG;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AI;QACJ,MAAM;QACN,MAAM;QACN,IAAI;QACJ,YAAY;QACZ,aAAa;QACb,eAAe;QACf,oBAAoB;QACpB,OAAO;QACP,SAAS;KACV,CACF,CAAC;IAEF,OAAO,uBAAC,iBAAiB,CAAC,QAAQ,IAAC,KAAK,EAAE,KAAK,YAAG,QAAQ,GAA8B,CAAC;AAC3F,CAAC;AAED;;;;;GAKG;AACH,SAAgB,aAAa;IAC3B,MAAM,GAAG,GAAG,IAAA,kBAAU,EAAC,iBAAiB,CAAC,CAAC;IAC1C,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,MAAM,IAAI,KAAK,CAAC,2DAA2D,CAAC,CAAC;IAC/E,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC"}
@@ -1,150 +1,2 @@
1
- export type SecureConversationType = "dm" | "group" | "channel";
2
- export type SecureMemberRole = "admin" | "member";
3
- export type SecureHandshakeKind = "welcome" | "commit" | "proposal";
4
- /** A Welcome targeted at the ONE device whose claimed KeyPackage was consumed. */
5
- export interface WelcomeEnvelope {
6
- targetDeviceId: string;
7
- payload: string;
8
- epoch: string;
9
- }
10
- /** A Commit/Proposal broadcast to the whole group (no target device). */
11
- export interface HandshakeBlob {
12
- payload: string;
13
- epoch: string;
14
- }
15
- export interface RegisterDeviceBody {
16
- deviceId: string;
17
- displayName?: string | null;
18
- signaturePublicKey: string;
19
- credential: string;
20
- ciphersuite: number;
21
- }
22
- export interface PublishKeyPackagesBody {
23
- keyPackages: {
24
- keyPackageRef: string;
25
- keyPackage: string;
26
- ciphersuite: number;
27
- expiresAt?: string | null;
28
- }[];
29
- }
30
- export interface CreateSecureConversationBody {
31
- type: SecureConversationType;
32
- mlsGroupId: string;
33
- spaceId?: string | null;
34
- name?: string | null;
35
- memberUserIds?: string[];
36
- welcomes?: WelcomeEnvelope[];
37
- }
38
- export interface AddSecureMemberBody {
39
- userId: string;
40
- commit: HandshakeBlob;
41
- welcomes: WelcomeEnvelope[];
42
- }
43
- export interface RemoveSecureMemberBody {
44
- commit: HandshakeBlob;
45
- }
46
- export interface SendSecureMessageBody {
47
- ciphertext: string;
48
- epoch: string;
49
- senderDeviceId: string;
50
- contentType?: string | null;
51
- }
52
- export interface UploadKeyBackupBody {
53
- deviceId?: string | null;
54
- blob: string;
55
- nonce: string;
56
- kdf: "argon2id" | "pbkdf2";
57
- kdfParams: Record<string, unknown>;
58
- cipher: "xchacha20poly1305" | "aes-256-gcm";
59
- version: number;
60
- }
61
- export interface SecureDeviceModel {
62
- id: string;
63
- projectId: string;
64
- userId: string;
65
- deviceId: string;
66
- displayName: string | null;
67
- signaturePublicKey: string;
68
- credential: string;
69
- ciphersuite: number;
70
- revokedAt: string | null;
71
- lastSeenAt: string | null;
72
- createdAt: string;
73
- updatedAt: string;
74
- }
75
- export interface SecureKeyPackageClaim {
76
- deviceId: string;
77
- keyPackageRef: string;
78
- keyPackage: string;
79
- ciphersuite: number;
80
- }
81
- export interface SecureConversationMemberModel {
82
- id: string;
83
- projectId: string;
84
- conversationId: string;
85
- userId: string;
86
- role: SecureMemberRole;
87
- isActive: boolean;
88
- joinedAtEpoch: string | null;
89
- lastReadAt: string | null;
90
- leftAt: string | null;
91
- createdAt: string;
92
- updatedAt: string;
93
- }
94
- export interface SecureConversationModel {
95
- id: string;
96
- projectId: string;
97
- type: SecureConversationType;
98
- mlsGroupId: string;
99
- spaceId: string | null;
100
- currentEpoch: string;
101
- name: string | null;
102
- createdById: string | null;
103
- lastMessageAt: string | null;
104
- memberCount?: number;
105
- unreadCount?: number;
106
- currentMember?: SecureConversationMemberModel;
107
- createdAt: string;
108
- updatedAt: string;
109
- }
110
- export interface SecureMessageModel {
111
- id: string;
112
- projectId: string;
113
- conversationId: string;
114
- senderUserId: string | null;
115
- senderDeviceId: string | null;
116
- epoch: string;
117
- ciphertext: string;
118
- contentType: string;
119
- createdAt: string;
120
- }
121
- export interface SecureHandshakeModel {
122
- id: string;
123
- seq: string;
124
- kind: SecureHandshakeKind;
125
- conversationId: string;
126
- epoch: string;
127
- payload: string;
128
- senderDeviceId: string | null;
129
- targetDeviceId: string | null;
130
- }
131
- export interface SecureKeyBackupModel {
132
- id: string;
133
- projectId: string;
134
- userId: string;
135
- deviceId: string | null;
136
- blob: string;
137
- nonce: string;
138
- kdf: string;
139
- kdfParams: Record<string, unknown>;
140
- cipher: string;
141
- version: number;
142
- createdAt: string;
143
- updatedAt: string;
144
- }
145
- /** Standard error envelope: `{ error, code, field? }` with `secure-chat/*` codes. */
146
- export interface SecureChatErrorBody {
147
- error: string;
148
- code: string;
149
- field?: string;
150
- }
1
+ export type { SecureDeviceModel, SecureKeyPackageClaim, SecureConversationMemberModel, SecureConversationModel, SecureMessageModel, SecureHandshakeModel, SecureKeyBackupModel, } from "@agora-server/contract";
2
+ export type { RegisterDeviceBody, PublishKeyPackagesBody, CreateSecureConversationBody, AddSecureMemberBody, RemoveSecureMemberBody, SendSecureMessageBody, UploadKeyBackupBody, WelcomeEnvelope, HandshakeBlob, } from "@agora-server/contract";
@@ -1,16 +1,17 @@
1
1
  "use strict";
2
- // Secure-chat wire contractstand-in for @agora-server/contract (the Apache-2.0 server contract).
2
+ // Secure-chat wire typesre-exported from the published `@agora-server/contract` (Apache-2.0).
3
3
  //
4
- // Mirrors the response models + request bodies of agora-server's
5
- // `packages/contract/src/secure-chat.ts`. That package is the source of truth (zod + TS); the
6
- // client only needs the TypeScript shapes, so this copy is types-only.
4
+ // The dependency arrow is **SDK contract**: agora-server owns the wire contract, this SDK depends
5
+ // on it. This module used to hold a byte-faithful *copy* of the types (a stand-in until the contract
6
+ // published); now that `@agora-server/contract` is published, it is a thin **type-only re-export** so
7
+ // there is exactly one source of truth and zero drift. The internal import path
8
+ // (`../contract/index.js`) is kept stable so call sites don't churn, and the re-export is scoped to
9
+ // the secure-chat surface (not the contract's reactions/pagination/etc.).
7
10
  //
8
- // ⚠️ Keep this byte-faithful to the server contract. The arrow is SDK contract: once
9
- // `@agora-server/contract` is published, DELETE this file and `import type { ... } from "@agora-server/contract"`.
10
- // Do NOT publish a separate `@agora-sdk/secure-chat-contract` (that would invert the dependency —
11
- // see STATUS.md). Do not let this copy drift in the meantime.
11
+ // Type-only on purpose: `@agora-server/contract` is ESM-only, but these `export type` re-exports are
12
+ // erased from the emitted JS, so core's dual ESM/CJS build never `require()`s it at runtime.
12
13
  //
13
- // Wire conventions: every binary value is **base64** (the server stores/relays opaque blobs and
14
- // never parses them); MLS epochs are **decimal strings** (u64 exceeds JS safe-int range).
14
+ // Wire conventions (owned by the contract): every binary value is **base64**; MLS epochs are
15
+ // **decimal strings** (u64 exceeds JS safe-int range).
15
16
  Object.defineProperty(exports, "__esModule", { value: true });
16
17
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/contract/index.ts"],"names":[],"mappings":";AAAA,oGAAoG;AACpG,EAAE;AACF,iEAAiE;AACjE,8FAA8F;AAC9F,uEAAuE;AACvE,EAAE;AACF,uFAAuF;AACvF,mHAAmH;AACnH,kGAAkG;AAClG,8DAA8D;AAC9D,EAAE;AACF,gGAAgG;AAChG,0FAA0F"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/contract/index.ts"],"names":[],"mappings":";AAAA,iGAAiG;AACjG,EAAE;AACF,oGAAoG;AACpG,qGAAqG;AACrG,sGAAsG;AACtG,gFAAgF;AAChF,oGAAoG;AACpG,0EAA0E;AAC1E,EAAE;AACF,qGAAqG;AACrG,6FAA6F;AAC7F,EAAE;AACF,6FAA6F;AAC7F,uDAAuD"}
@@ -0,0 +1,67 @@
1
+ import { type PassphraseStrength } from "../backup/passphrase-strength.js";
2
+ /** State + actions returned by {@link useSecureBackup}. */
3
+ export interface UseSecureBackupValues {
4
+ /**
5
+ * Seal all local key material under `passphrase` and upload it to the blind server.
6
+ * @throws {Error} If export or upload fails.
7
+ */
8
+ backup: (passphrase: string) => Promise<void>;
9
+ /**
10
+ * Restore local key material on a fresh client from the server's backup, rehydrating the device and
11
+ * every conversation's group state.
12
+ * @throws {Error} If no backup exists, the passphrase is wrong, or the backup is corrupt.
13
+ */
14
+ restore: (passphrase: string) => Promise<void>;
15
+ /** True while {@link UseSecureBackupValues.backup} is in flight. */
16
+ backingUp: boolean;
17
+ /** True while {@link UseSecureBackupValues.restore} is in flight. */
18
+ restoring: boolean;
19
+ /** The last error thrown by backup or restore, or `null`. */
20
+ error: unknown;
21
+ /** Server `updatedAt` of the most recent successful upload this session, or `null`. */
22
+ lastBackupAt: string | null;
23
+ /** True once a group has advanced since the last backup (membership/epoch change) — prompt a re-backup. */
24
+ needsBackup: boolean;
25
+ /**
26
+ * True when there is NO local key material but a backup exists on the server — i.e. this client was
27
+ * evicted (Safari ITP / "clear browsing data") or is a fresh browser, and recovery is possible. The
28
+ * app should route to a passphrase prompt → {@link UseSecureBackupValues.restore} instead of
29
+ * registering a new device. Indistinguishable cases (evicted vs cleared vs new browser) all resolve
30
+ * the same way. Cleared after a successful restore.
31
+ */
32
+ needsRestore: boolean;
33
+ /** True while the mount-time eviction check (or {@link UseSecureBackupValues.recheckRestore}) is in flight. */
34
+ checkingRestore: boolean;
35
+ /**
36
+ * Re-run the eviction check on demand (e.g. after catching a storage error mid-session, or after
37
+ * sign-in). Skips the server entirely when local key material is present.
38
+ * @returns The new {@link UseSecureBackupValues.needsRestore} value.
39
+ */
40
+ recheckRestore: () => Promise<boolean>;
41
+ /** Coarse client-side passphrase-strength estimate for a meter (see {@link estimatePassphraseStrength}). */
42
+ estimateStrength: (passphrase: string) => PassphraseStrength;
43
+ }
44
+ /**
45
+ * Manage passphrase backup + restore of the client's secure-chat key material.
46
+ *
47
+ * Backups are explicit (call {@link UseSecureBackupValues.backup}); `needsBackup` flips true when a
48
+ * group advances so the app can prompt. On mount it also detects an evicted/fresh client
49
+ * (`needsRestore`) so the app restores rather than registering a fresh, history-less identity.
50
+ *
51
+ * @returns Backup/restore actions, the evicted-client `needsRestore` signal, in-flight + error state, a
52
+ * stale-backup signal, and a passphrase-strength helper.
53
+ * @throws {Error} When used outside a `<SecureChatProvider>`.
54
+ *
55
+ * @example
56
+ * ```tsx
57
+ * const { needsRestore, restore, backup } = useSecureBackup();
58
+ * const { device, register } = useSecureDevice();
59
+ * // Route an evicted / fresh client to restore; a true first-run to register.
60
+ * if (needsRestore) await restore(passphrase); // prompt for the passphrase first
61
+ * else if (!device) await register();
62
+ * await backup(passphrase); // later, after a device/chat exists
63
+ * ```
64
+ * Restore should complete before the app relies on `useSecureDevice` (which read `device: null` on its
65
+ * own mount) — gate the chat subtree on a post-restore flag or remount it after restore.
66
+ */
67
+ export declare function useSecureBackup(): UseSecureBackupValues;
@@ -0,0 +1,207 @@
1
+ "use strict";
2
+ // useSecureBackup — passphrase backup + restore of all local key material.
3
+ //
4
+ // Backup: crypto.exportBackup(passphrase) seals the device identity + every group's state under a
5
+ // real argon2id KDF + AEAD; we base64 the blob/nonce at the wire boundary and PUT it to the blind
6
+ // server, which stores the ciphertext verbatim (it never sees the passphrase or plaintext).
7
+ //
8
+ // Restore (fresh browser): GET the blob → crypto.importBackup re-derives the identity + groups in
9
+ // memory → re-assert the device server-side (idempotent) to recover its row → persist the device →
10
+ // rebind each conversation's group state by conversationId from the server's conversation list (the
11
+ // server is the source of truth for membership; the backup itself is conversationId-agnostic). The
12
+ // handshake cursor is intentionally left unset so useSecureHandshakes re-pulls from since=0 and
13
+ // dedupes — no cursor needs to live in the backup.
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.useSecureBackup = useSecureBackup;
16
+ const react_1 = require("react");
17
+ const base64_js_1 = require("../util/base64.js");
18
+ const secure_chat_context_js_1 = require("../context/secure-chat-context.js");
19
+ const passphrase_strength_js_1 = require("../backup/passphrase-strength.js");
20
+ /**
21
+ * Manage passphrase backup + restore of the client's secure-chat key material.
22
+ *
23
+ * Backups are explicit (call {@link UseSecureBackupValues.backup}); `needsBackup` flips true when a
24
+ * group advances so the app can prompt. On mount it also detects an evicted/fresh client
25
+ * (`needsRestore`) so the app restores rather than registering a fresh, history-less identity.
26
+ *
27
+ * @returns Backup/restore actions, the evicted-client `needsRestore` signal, in-flight + error state, a
28
+ * stale-backup signal, and a passphrase-strength helper.
29
+ * @throws {Error} When used outside a `<SecureChatProvider>`.
30
+ *
31
+ * @example
32
+ * ```tsx
33
+ * const { needsRestore, restore, backup } = useSecureBackup();
34
+ * const { device, register } = useSecureDevice();
35
+ * // Route an evicted / fresh client to restore; a true first-run to register.
36
+ * if (needsRestore) await restore(passphrase); // prompt for the passphrase first
37
+ * else if (!device) await register();
38
+ * await backup(passphrase); // later, after a device/chat exists
39
+ * ```
40
+ * Restore should complete before the app relies on `useSecureDevice` (which read `device: null` on its
41
+ * own mount) — gate the chat subtree on a post-restore flag or remount it after restore.
42
+ */
43
+ function useSecureBackup() {
44
+ const { crypto, rest, repo, rememberGroup, subscribeGroupChange } = (0, secure_chat_context_js_1.useSecureChat)();
45
+ const [backingUp, setBackingUp] = (0, react_1.useState)(false);
46
+ const [restoring, setRestoring] = (0, react_1.useState)(false);
47
+ const [error, setError] = (0, react_1.useState)(null);
48
+ const [lastBackupAt, setLastBackupAt] = (0, react_1.useState)(null);
49
+ const [needsBackup, setNeedsBackup] = (0, react_1.useState)(false);
50
+ const [needsRestore, setNeedsRestore] = (0, react_1.useState)(false);
51
+ const [checkingRestore, setCheckingRestore] = (0, react_1.useState)(false);
52
+ // A group advancing (a join or a processed Commit) means the on-server backup is now stale.
53
+ // Guard the very first synchronous fire so mount doesn't immediately flag a backup as needed.
54
+ const armed = (0, react_1.useRef)(false);
55
+ (0, react_1.useEffect)(() => {
56
+ armed.current = true;
57
+ return subscribeGroupChange(() => {
58
+ if (armed.current)
59
+ setNeedsBackup(true);
60
+ });
61
+ }, [subscribeGroupChange]);
62
+ // Eviction / fresh-client detection: local key material gone but a server backup exists ⇒ restore is
63
+ // possible (and preferable to registering a new, history-less identity). Evicted, "cleared browsing
64
+ // data", and a brand-new browser are indistinguishable here and resolve the same way. We only hit the
65
+ // server when there's no local device, so the common (healthy) path stays a single IndexedDB read.
66
+ const recheckRestore = (0, react_1.useCallback)(async () => {
67
+ setCheckingRestore(true);
68
+ try {
69
+ const persisted = await repo.loadDevice();
70
+ if (persisted) {
71
+ setNeedsRestore(false);
72
+ return false;
73
+ }
74
+ const model = await rest.getKeyBackup();
75
+ const possible = model !== null;
76
+ setNeedsRestore(possible);
77
+ return possible;
78
+ }
79
+ catch (err) {
80
+ // Fail soft: a network blip must not strand the user as "needs restore". Surface the error only.
81
+ setError(err);
82
+ setNeedsRestore(false);
83
+ return false;
84
+ }
85
+ finally {
86
+ setCheckingRestore(false);
87
+ }
88
+ }, [repo, rest]);
89
+ (0, react_1.useEffect)(() => {
90
+ let alive = true;
91
+ repo
92
+ .loadDevice()
93
+ .then(async (persisted) => {
94
+ if (!alive || persisted)
95
+ return; // have local state → not evicted; skip the server call
96
+ const model = await rest.getKeyBackup();
97
+ if (alive)
98
+ setNeedsRestore(model !== null);
99
+ })
100
+ .catch((err) => {
101
+ if (alive)
102
+ setError(err); // fail soft
103
+ });
104
+ return () => {
105
+ alive = false;
106
+ };
107
+ }, [repo, rest]);
108
+ const backup = (0, react_1.useCallback)(async (passphrase) => {
109
+ setBackingUp(true);
110
+ setError(null);
111
+ try {
112
+ const b = await crypto.exportBackup(passphrase);
113
+ const { updatedAt } = await rest.uploadKeyBackup({
114
+ // base64 at the wire boundary; KDF params (incl. the hex salt) are non-secret metadata.
115
+ blob: (0, base64_js_1.toBase64)(b.blob),
116
+ nonce: (0, base64_js_1.toBase64)(b.nonce),
117
+ kdf: b.kdf,
118
+ kdfParams: b.kdfParams,
119
+ cipher: b.cipher,
120
+ version: b.version,
121
+ });
122
+ setLastBackupAt(updatedAt);
123
+ setNeedsBackup(false);
124
+ }
125
+ catch (err) {
126
+ setError(err);
127
+ throw err;
128
+ }
129
+ finally {
130
+ setBackingUp(false);
131
+ }
132
+ }, [crypto, rest]);
133
+ const restore = (0, react_1.useCallback)(async (passphrase) => {
134
+ setRestoring(true);
135
+ setError(null);
136
+ try {
137
+ const model = await rest.getKeyBackup();
138
+ if (!model)
139
+ throw new Error("No key backup found on the server to restore.");
140
+ // Decrypt + repopulate crypto memory (identity + groups). Returns the restored identity.
141
+ const id = await crypto.importBackup(passphrase, {
142
+ blob: (0, base64_js_1.fromBase64)(model.blob),
143
+ nonce: (0, base64_js_1.fromBase64)(model.nonce),
144
+ kdf: model.kdf,
145
+ kdfParams: model.kdfParams,
146
+ cipher: model.cipher,
147
+ version: model.version,
148
+ });
149
+ // Re-assert the (already-registered) device to recover its server row — idempotent on
150
+ // (userId, deviceId). The row's id is the senderDeviceId messages need.
151
+ const device = await rest.registerDevice({
152
+ deviceId: id.deviceId,
153
+ signaturePublicKey: (0, base64_js_1.toBase64)(id.signaturePublicKey),
154
+ credential: (0, base64_js_1.toBase64)(id.credential),
155
+ ciphersuite: id.ciphersuite,
156
+ });
157
+ await repo.saveDevice({
158
+ deviceId: id.deviceId,
159
+ deviceState: await crypto.exportDeviceState(),
160
+ device,
161
+ });
162
+ // Rebind conversationId → restored group state from the server's conversation list.
163
+ let cursor;
164
+ for (;;) {
165
+ const page = await rest.listConversations(cursor ? { cursor } : undefined);
166
+ for (const c of page.conversations) {
167
+ try {
168
+ await rememberGroup(c.id, {
169
+ mlsGroupId: (0, base64_js_1.fromBase64)(c.mlsGroupId),
170
+ epoch: BigInt(c.currentEpoch),
171
+ });
172
+ }
173
+ catch {
174
+ // The group isn't in this backup (created after it, or we're not a member) — skip it.
175
+ }
176
+ }
177
+ if (!page.hasMore || page.conversations.length === 0)
178
+ break;
179
+ const last = page.conversations[page.conversations.length - 1];
180
+ cursor = last.lastMessageAt ?? last.createdAt;
181
+ }
182
+ setNeedsBackup(false);
183
+ setNeedsRestore(false); // we now hold local key material again
184
+ }
185
+ catch (err) {
186
+ setError(err);
187
+ throw err;
188
+ }
189
+ finally {
190
+ setRestoring(false);
191
+ }
192
+ }, [crypto, rest, repo, rememberGroup]);
193
+ return {
194
+ backup,
195
+ restore,
196
+ backingUp,
197
+ restoring,
198
+ error,
199
+ lastBackupAt,
200
+ needsBackup,
201
+ needsRestore,
202
+ checkingRestore,
203
+ recheckRestore,
204
+ estimateStrength: passphrase_strength_js_1.estimatePassphraseStrength,
205
+ };
206
+ }
207
+ //# sourceMappingURL=useSecureBackup.js.map