@jini-ai/platform 0.7.3-next.2 → 0.7.4

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 (141) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +13 -0
  3. package/dist/download-lock.d.ts +3 -1
  4. package/dist/download-lock.js +4 -6
  5. package/dist/download-maintenance.js +6 -6
  6. package/dist/download-state.js +17 -14
  7. package/dist/download-store.d.ts +34 -10
  8. package/dist/download-store.js +24 -20
  9. package/dist/download-target.d.ts +6 -2
  10. package/dist/download-target.js +7 -7
  11. package/dist/download-transfer.js +18 -12
  12. package/dist/download.js +4 -4
  13. package/dist/fetch-with-timeout.d.ts +0 -53
  14. package/dist/fetch-with-timeout.js +62 -13
  15. package/dist/fs/directory-running-lock.d.ts +4 -0
  16. package/dist/fs/directory-running-lock.js +8 -1
  17. package/dist/fs/directory-workspace.d.ts +2 -1
  18. package/dist/fs/directory-workspace.js +2 -2
  19. package/dist/fs/durable-json.d.ts +3 -16
  20. package/dist/fs/durable-json.js +4 -2
  21. package/dist/fs/guarded-reader.d.ts +10 -0
  22. package/dist/fs/guarded-reader.js +34 -1
  23. package/dist/fs/index.d.ts +4 -0
  24. package/dist/fs/index.js +4 -0
  25. package/dist/fs/leased-directory-move.d.ts +49 -0
  26. package/dist/fs/leased-directory-move.js +31 -0
  27. package/dist/fs/owned-temp-root.d.ts +74 -0
  28. package/dist/fs/owned-temp-root.js +203 -0
  29. package/dist/fs/recent-directories.d.ts +2 -1
  30. package/dist/fs/resolve-directory-target.d.ts +33 -0
  31. package/dist/fs/resolve-directory-target.js +58 -0
  32. package/dist/fs/staged-file.d.ts +40 -0
  33. package/dist/fs/staged-file.js +75 -0
  34. package/dist/fs/strict-containment.d.ts +14 -0
  35. package/dist/fs/strict-containment.js +14 -0
  36. package/dist/image/png-encode.d.ts +41 -0
  37. package/dist/image/png-encode.js +96 -0
  38. package/dist/index.d.ts +3 -1
  39. package/dist/mail/email-template-agent-tools.d.ts +150 -0
  40. package/dist/mail/email-template-agent-tools.js +86 -0
  41. package/dist/mail/email-template-tool-registrations.d.ts +73 -0
  42. package/dist/mail/email-template-tool-registrations.js +66 -0
  43. package/dist/mail/email-template.js +3 -7
  44. package/dist/mail/feedback-route.d.ts +50 -0
  45. package/dist/mail/feedback-route.js +46 -0
  46. package/dist/mail/feedback-setup.d.ts +44 -0
  47. package/dist/mail/feedback-setup.js +53 -0
  48. package/dist/mail/feedback-sources.d.ts +67 -0
  49. package/dist/mail/feedback-sources.js +42 -0
  50. package/dist/mail/index.d.ts +10 -1
  51. package/dist/mail/index.js +4 -0
  52. package/dist/mail/mail-status.d.ts +32 -0
  53. package/dist/mail/mail-status.js +2 -0
  54. package/dist/mail/positional-purpose-gate.d.ts +14 -0
  55. package/dist/mail/positional-purpose-gate.js +18 -0
  56. package/dist/mail/purpose-gate-probe.d.ts +18 -0
  57. package/dist/mail/purpose-gate-probe.js +22 -0
  58. package/dist/mail/purpose-scoped-mailer.d.ts +4 -0
  59. package/dist/mail/purpose-scoped-mailer.js +4 -3
  60. package/dist/mail/resolve-mailer.d.ts +13 -1
  61. package/dist/mail/resolve-mailer.js +11 -5
  62. package/dist/mail/sql/activity.repo.d.ts +20 -0
  63. package/dist/mail/sql/activity.repo.js +133 -0
  64. package/dist/mail/sql/attempts.repo.d.ts +17 -0
  65. package/dist/mail/sql/attempts.repo.js +32 -0
  66. package/dist/mail/sql/capture.repo.d.ts +69 -0
  67. package/dist/mail/sql/capture.repo.js +119 -0
  68. package/dist/mail/sql/feedback-inbox.repo.d.ts +12 -0
  69. package/dist/mail/sql/feedback-inbox.repo.js +32 -0
  70. package/dist/mail/sql/index.d.ts +12 -0
  71. package/dist/mail/sql/index.js +12 -0
  72. package/dist/mail/sql/ledger.repo.d.ts +29 -0
  73. package/dist/mail/sql/ledger.repo.js +57 -0
  74. package/dist/mail/sql/retention.d.ts +23 -0
  75. package/dist/mail/sql/retention.js +53 -0
  76. package/dist/mail/sql/site-feedback-route.d.ts +18 -0
  77. package/dist/mail/sql/site-feedback-route.js +22 -0
  78. package/dist/mail/sql/suppression-admin.repo.d.ts +11 -0
  79. package/dist/mail/sql/suppression-admin.repo.js +76 -0
  80. package/dist/mail/sql/suppression.repo.d.ts +10 -0
  81. package/dist/mail/sql/suppression.repo.js +33 -0
  82. package/dist/mail/test-send.d.ts +147 -0
  83. package/dist/mail/test-send.js +198 -0
  84. package/dist/mail/use-readiness.d.ts +104 -0
  85. package/dist/mail/use-readiness.js +140 -0
  86. package/dist/object-store/local-fs.js +34 -1
  87. package/dist/object-store/site/artifact-provider.d.ts +65 -0
  88. package/dist/object-store/site/artifact-provider.js +37 -0
  89. package/dist/object-store/site/registry.d.ts +110 -0
  90. package/dist/object-store/site/registry.js +93 -0
  91. package/dist/object-store/site/setting.d.ts +34 -0
  92. package/dist/object-store/site/setting.js +32 -0
  93. package/dist/process-probes.d.ts +11 -4
  94. package/dist/process-probes.js +3 -3
  95. package/dist/process-top-footprint.d.ts +1 -1
  96. package/dist/process-top-footprint.js +1 -3
  97. package/dist/process.d.ts +3 -17
  98. package/dist/process.js +3 -2
  99. package/dist/retention/index.d.ts +6 -0
  100. package/dist/retention/index.js +6 -0
  101. package/dist/retention/measure-tree.d.ts +68 -0
  102. package/dist/retention/measure-tree.js +205 -0
  103. package/dist/retention/preview-store.d.ts +12 -0
  104. package/dist/retention/preview-store.js +28 -0
  105. package/dist/retention/routes.d.ts +23 -0
  106. package/dist/retention/routes.js +24 -0
  107. package/dist/retention/runner.d.ts +103 -0
  108. package/dist/retention/runner.js +164 -0
  109. package/dist/secrets/credential-sets/index.d.ts +1 -0
  110. package/dist/secrets/credential-sets/index.js +1 -0
  111. package/dist/secrets/credential-sets/store-vault-guards.d.ts +26 -0
  112. package/dist/secrets/credential-sets/store-vault-guards.js +30 -0
  113. package/dist/secrets/credential-sets/vault.service.d.ts +1 -1
  114. package/dist/secrets/index.d.ts +1 -1
  115. package/dist/secrets/index.js +1 -1
  116. package/dist/secrets/keyring.env.d.ts +1 -1
  117. package/dist/secrets/keyring.env.js +3 -5
  118. package/dist/secrets/keyring.memory.d.ts +4 -1
  119. package/dist/secrets/keyring.memory.js +4 -1
  120. package/dist/secrets/legacy-codecs.d.ts +381 -0
  121. package/dist/secrets/legacy-codecs.js +468 -0
  122. package/dist/secrets/legacy-owner.d.ts +3 -11
  123. package/dist/secrets/root-key/ensure.d.ts +154 -0
  124. package/dist/secrets/root-key/ensure.js +328 -0
  125. package/dist/secrets/root-key/files.d.ts +104 -0
  126. package/dist/secrets/root-key/files.js +166 -0
  127. package/dist/secrets/root-key/material.d.ts +132 -0
  128. package/dist/secrets/root-key/material.js +116 -0
  129. package/dist/secrets/root-key/ordered-keyring.d.ts +157 -0
  130. package/dist/secrets/root-key/ordered-keyring.js +104 -0
  131. package/dist/secrets/root-key/reconcile.d.ts +50 -0
  132. package/dist/secrets/root-key/reconcile.js +147 -0
  133. package/dist/secrets/root-key/site-keyring-errors.d.ts +78 -0
  134. package/dist/secrets/root-key/site-keyring-errors.js +37 -0
  135. package/dist/secrets/root-key/sources.d.ts +79 -0
  136. package/dist/secrets/root-key/sources.js +119 -0
  137. package/dist/secrets/secret-sealer.aesgcm.d.ts +50 -2
  138. package/dist/secrets/secret-sealer.aesgcm.js +107 -19
  139. package/dist/web/tool-registrations.d.ts +67 -0
  140. package/dist/web/tool-registrations.js +44 -0
  141. package/package.json +138 -6
@@ -0,0 +1,147 @@
1
+ import { decideLocalSiteKeyEnsure, matchesFingerprint, verdictOf } from "./decide.js";
2
+ import { fingerprintRootKeyHex, parseRootKeyHex } from "../keyring.env.js";
3
+ export async function reconcileRootKey({ ports }, _optional = {}) {
4
+ const perSiteRaw = ports.readPerSite({});
5
+ const perSiteParsed = perSiteRaw === undefined ? undefined : parseRootKeyHex({ raw: perSiteRaw });
6
+ // A source holding exactly the key `.site-meta.json` names is the right one to adopt wherever it
7
+ // sits in the order; only without such a source does the first-present rule apply.
8
+ const stampedFingerprint = ports.stampedFingerprint;
9
+ const stampedHex = findStampedHex({ others: ports.others, stampedFingerprint });
10
+ // A per-site file the stamp does not name (a different key, or malformed) while another source
11
+ // holds the stamped key: the per-site file would otherwise outrank the right key forever. It is
12
+ // moved aside, never deleted, and the stamped key takes its place.
13
+ if (perSiteRaw !== undefined && stampedHex !== undefined && !matchesFingerprint({ parsed: perSiteParsed, fingerprint: stampedFingerprint })) {
14
+ ports.moveAside({ expectedContent: perSiteRaw });
15
+ const written = ports.createExclusive({ hex: stampedHex });
16
+ return reconcileStamp({ ports, action: "adopt", fingerprint: fingerprintRootKeyHex({ hex: written }), mayRestamp: neverRestamp });
17
+ }
18
+ return settle({
19
+ ports,
20
+ perSite: verdictOf({ parsed: perSiteParsed }),
21
+ other: stampedHex !== undefined ? { kind: "valid", value: stampedHex } : verdictOf({ parsed: firstPresent({ others: ports.others }) }),
22
+ stampedFingerprint,
23
+ });
24
+ }
25
+ async function settle(required) {
26
+ const { ports, perSite, other } = required;
27
+ let hasKeyDataMemo;
28
+ const siteHasKeyData = async () => {
29
+ hasKeyDataMemo ??= await ports.hasDependentData({});
30
+ return hasKeyDataMemo;
31
+ };
32
+ const needsDataCheck = perSite.kind === "absent" && other.kind === "absent";
33
+ const siteDbsWithKeyData = needsDataCheck ? await siteHasKeyData() : false;
34
+ const decision = decideLocalSiteKeyEnsure({ perSite, other, siteDbsWithKeyData });
35
+ switch (decision.action) {
36
+ case "noop":
37
+ return reconcileStamp({ ports, action: "noop", fingerprint: fingerprintRootKeyHex({ hex: decision.value }), mayRestamp: neverRestamp });
38
+ case "invalid":
39
+ return { action: "invalid", reason: decision.value };
40
+ case "adopt":
41
+ return adopt({ ports, hex: decision.value, stampedFingerprint: required.stampedFingerprint, siteHasKeyData });
42
+ case "refuse":
43
+ return { action: "refuse" };
44
+ case "mint": {
45
+ const written = ports.createExclusive({ hex: ports.mint({}) });
46
+ // `mint` is only planned when the site has no key-dependent data, so a stale stamp (a moved or
47
+ // copied site folder) protects nothing — it is replaced rather than left as a permanent,
48
+ // false "mismatch".
49
+ return reconcileStamp({ ports, action: "mint", fingerprint: fingerprintRootKeyHex({ hex: written }), mayRestamp: async () => !(await siteHasKeyData()) });
50
+ }
51
+ default: {
52
+ const unhandled = decision;
53
+ throw new TypeError(`Unknown site key decision: ${String(unhandled)}`);
54
+ }
55
+ }
56
+ }
57
+ /** The `"adopt"` outcome: copies `hex` (another source's valid key) into the per-site file. */
58
+ async function adopt(required) {
59
+ const { ports, hex, stampedFingerprint, siteHasKeyData } = required;
60
+ // The stamp is checked BEFORE the write: once a per-site file exists it outranks every other
61
+ // source, so adopting a key the stamp already proves wrong would make it permanent and block
62
+ // the right key from ever being adopted. With no key-dependent data the stamp protects
63
+ // nothing, so adoption goes ahead and the stamp is updated.
64
+ const candidateFingerprint = fingerprintRootKeyHex({ hex });
65
+ if (stampedFingerprint !== undefined && stampedFingerprint !== candidateFingerprint && (await siteHasKeyData())) {
66
+ return { action: "mismatch", fingerprint: candidateFingerprint };
67
+ }
68
+ const written = ports.createExclusive({ hex });
69
+ return reconcileStamp({ ports, action: "adopt", fingerprint: fingerprintRootKeyHex({ hex: written }), mayRestamp: async () => !(await siteHasKeyData()) });
70
+ }
71
+ /** `mayRestamp` for outcomes that never re-stamp (`"noop"`, and replacing a per-site file with the
72
+ * stamped key): a differing stamp there is evidence, reported as `"mismatch"`. */
73
+ const neverRestamp = async () => false;
74
+ /**
75
+ * Site-key plan §A.2's fingerprint stamp / §A.4: after `ensureSiteKey` settles on the key now
76
+ * actually in the per-site file (`"noop"`, `"adopt"`, or `"mint"`), makes sure `.site-meta.json`
77
+ * records that key's fingerprint — atomically, and preserving every other field in the file — so a
78
+ * LATER substitution of the physical key file becomes visible before any decrypt ever fails on it
79
+ * (§A.5's `"mismatch"` banner state).
80
+ *
81
+ * - No readable/parseable `.site-meta.json` at `siteDir` → nothing to stamp against; the caller's
82
+ * own key-material outcome is untouched. This keeps every pre-A4 `ensureSiteKey` caller (a raw
83
+ * temp `siteDir` with no meta file at all, e.g. this module's own unit-test fixtures) working
84
+ * exactly as before this stamp existed.
85
+ * - Field absent → stamped now, merged into the EXISTING parsed object so no other field is lost or
86
+ * reset (never a fresh object built from scratch).
87
+ * - Field present and equal → nothing written; the file already reflects reality.
88
+ * - Field present and different, and `mayRestamp()` is false (the site has key-dependent data, or
89
+ * the caller is `"noop"`) → the stamp is evidence, not a cache: this call returns `"mismatch"`
90
+ * instead of the caller's own action and does not rewrite `.site-meta.json`.
91
+ * - Field present and different, and `mayRestamp()` is true (`"mint"`/`"adopt"` on a site with no
92
+ * key-dependent data — nothing sealed under the stamped key can be orphaned) → re-stamped to the
93
+ * key now in the file, and the caller's own action is returned.
94
+ *
95
+ * @complexity O(1) — one bounded JSON read, at most one atomic JSON write.
96
+ */
97
+ async function reconcileStamp({ ports, action, fingerprint, mayRestamp, }, _optional = {}) {
98
+ // `readSiteMetaJson` (site-key-sources.ts) — the shared `.site-meta.json` parse both this
99
+ // function and `site-key-sources.ts`'s own `resolveSiteKeyId`/`resolveSiteKeyFingerprint` build
100
+ // on, so a corrupt-file/non-object verdict can never drift between the writer's own
101
+ // reconciliation and the admin route's read-only state derivation.
102
+ const stamp = ports.readStamp({});
103
+ if (stamp.kind === "no-meta") {
104
+ return { action, fingerprint };
105
+ }
106
+ const stamped = stamp.fingerprint;
107
+ if (stamped === undefined) {
108
+ stamp.write({ fingerprint });
109
+ return { action, fingerprint };
110
+ }
111
+ if (stamped === fingerprint) {
112
+ return { action, fingerprint };
113
+ }
114
+ if (await mayRestamp()) {
115
+ stamp.write({ fingerprint });
116
+ return { action, fingerprint };
117
+ }
118
+ return { action: "mismatch", fingerprint };
119
+ }
120
+ /** The (trimmed) key of the first source in `sources` holding a valid key whose fingerprint is
121
+ * `stampedFingerprint`, or `undefined` when nothing is stamped or no source matches. A match is
122
+ * proof it is the key the site's data was sealed with, so a broken or different source earlier in
123
+ * the order does not hide it.
124
+ * @complexity O(n) in `sources.length` — one read and one hash per source. */
125
+ function findStampedHex({ others, stampedFingerprint, }, _optional = {}) {
126
+ if (stampedFingerprint === undefined)
127
+ return undefined;
128
+ for (const read of others) {
129
+ const raw = read({});
130
+ const parsed = raw === undefined ? undefined : parseRootKeyHex({ raw });
131
+ if (parsed?.ok && fingerprintRootKeyHex({ hex: parsed.hex }) === stampedFingerprint)
132
+ return parsed.hex;
133
+ }
134
+ return undefined;
135
+ }
136
+ /** The first source in `sources` that has ANY material — present-but-invalid still counts and
137
+ * stops the scan (site-key plan §A.2: adopting silently past a broken source would still be
138
+ * wrong, the same reasoning `keyring.env.ts`'s own env-then-file resolution already follows). */
139
+ function firstPresent({ others }, _optional = {}) {
140
+ for (const read of others) {
141
+ const raw = read({});
142
+ if (raw !== undefined)
143
+ return parseRootKeyHex({ raw });
144
+ }
145
+ return undefined;
146
+ }
147
+ //# sourceMappingURL=reconcile.js.map
@@ -0,0 +1,78 @@
1
+ import type { RootKeyRejection } from '../keyring.env.js';
2
+ import type { SiteKeySource } from './material.js';
3
+ export declare function createSiteKeyringErrors(required: {
4
+ UnusableSiteKeyError: abstract new (...args: never[]) => Error & {
5
+ source: 'env' | 'file';
6
+ reason: RootKeyRejection;
7
+ };
8
+ describeSource(source: SiteKeySource): string;
9
+ copy: {
10
+ envVarName: string;
11
+ fileWarningSubject: string;
12
+ envWarningSubject: string;
13
+ rejectionDetail: Record<RootKeyRejection, (required: {
14
+ hexDigits: number;
15
+ }) => string>;
16
+ refusal(required: {
17
+ subject: string;
18
+ detail: string;
19
+ }): string;
20
+ sealedWarning(required: {
21
+ subject: string;
22
+ }): string;
23
+ alreadyExists(required: {
24
+ keyFilePath: string;
25
+ }): string;
26
+ rootRefusal: string;
27
+ siteRefusal: string;
28
+ };
29
+ }, _optional?: {}): {
30
+ UnusableSiteKeyError: {
31
+ new (input: {
32
+ source: "env" | "file";
33
+ reason: RootKeyRejection;
34
+ message: string;
35
+ }): {
36
+ readonly source: "env" | "file";
37
+ readonly reason: RootKeyRejection;
38
+ name: string;
39
+ message: string;
40
+ stack?: string;
41
+ cause?: unknown;
42
+ };
43
+ captureStackTrace(targetObject: object, constructorOpt?: Function): void;
44
+ prepareStackTrace(err: Error, stackTraces: NodeJS.CallSite[]): any;
45
+ stackTraceLimit: number;
46
+ };
47
+ SiteKeyFileAlreadyExistsError: {
48
+ new (input: {
49
+ keyFilePath: string;
50
+ }): {
51
+ name: string;
52
+ message: string;
53
+ stack?: string;
54
+ cause?: unknown;
55
+ };
56
+ captureStackTrace(targetObject: object, constructorOpt?: Function): void;
57
+ prepareStackTrace(err: Error, stackTraces: NodeJS.CallSite[]): any;
58
+ stackTraceLimit: number;
59
+ };
60
+ unusableSiteKeyError: ({ source, rejection }: {
61
+ source: SiteKeySource;
62
+ rejection: {
63
+ reason: RootKeyRejection;
64
+ hexDigits: number;
65
+ };
66
+ }) => {
67
+ readonly source: "env" | "file";
68
+ readonly reason: RootKeyRejection;
69
+ name: string;
70
+ message: string;
71
+ stack?: string;
72
+ cause?: unknown;
73
+ };
74
+ rethrowKeyringError: ({ error }: {
75
+ error: unknown;
76
+ }) => never;
77
+ };
78
+ //# sourceMappingURL=site-keyring-errors.d.ts.map
@@ -0,0 +1,37 @@
1
+ export function createSiteKeyringErrors(required, _optional = {}) {
2
+ class UnusableSiteKeyError extends Error {
3
+ source;
4
+ reason;
5
+ constructor(input) {
6
+ super(input.message);
7
+ this.name = 'UnusableSiteKeyError';
8
+ this.source = input.source;
9
+ this.reason = input.reason;
10
+ }
11
+ }
12
+ class SiteKeyFileAlreadyExistsError extends Error {
13
+ constructor(input) {
14
+ super(required.copy.alreadyExists(input));
15
+ this.name = 'SiteKeyFileAlreadyExistsError';
16
+ }
17
+ }
18
+ return {
19
+ UnusableSiteKeyError, SiteKeyFileAlreadyExistsError,
20
+ unusableSiteKeyError: ({ source, rejection }) => {
21
+ const isEnv = source.kind === 'env';
22
+ const subject = isEnv ? required.copy.envVarName : required.describeSource(source);
23
+ const detail = required.copy.rejectionDetail[rejection.reason]({ hexDigits: rejection.hexDigits });
24
+ const sealedWarningSubject = !isEnv ? required.copy.fileWarningSubject : rejection.reason === 'too-short' ? required.copy.envWarningSubject : undefined;
25
+ const refusal = required.copy.refusal({ subject, detail });
26
+ return new UnusableSiteKeyError({ source: isEnv ? 'env' : 'file', reason: rejection.reason,
27
+ message: sealedWarningSubject === undefined ? refusal : refusal + required.copy.sealedWarning({ subject: sealedWarningSubject }),
28
+ });
29
+ },
30
+ rethrowKeyringError: ({ error }) => {
31
+ if (error instanceof required.UnusableSiteKeyError)
32
+ throw new UnusableSiteKeyError({ source: error.source, reason: error.reason, message: error.message.replace(required.copy.rootRefusal, () => required.copy.siteRefusal) });
33
+ throw error;
34
+ },
35
+ };
36
+ }
37
+ //# sourceMappingURL=site-keyring-errors.js.map
@@ -0,0 +1,79 @@
1
+ import type { RuntimeMode } from "@jini-ai/core/contracts/site/core-runtime-mode";
2
+ import { type SiteKeySource } from "./material.js";
3
+ type SiteKeySourcesInput = {
4
+ readonly mode: RuntimeMode;
5
+ readonly env: Record<string, string | undefined>;
6
+ readonly home: string;
7
+ readonly cwd: string;
8
+ readonly siteKeyId?: string | undefined;
9
+ };
10
+ /** Whether `id` can be used as a key-file name without escaping the configured site-key directory. */
11
+ export declare function isSafeSiteKeyId({ id }: {
12
+ id: string;
13
+ }, _optional?: {}): boolean;
14
+ /**
15
+ * Whether a value may name a site: a UUID-like short token (letters, digits, `-`, `_`; at most 64).
16
+ * A site id travels into provider signals and, through the host's deployment configuration command, into a generated config
17
+ * file's env block, so a hand-edited or hostile `.site-meta.json` / the host's site-id env var (a newline, quotes,
18
+ * a path) is refused rather than carried.
19
+ * @complexity O(1) (bounded length).
20
+ */
21
+ export declare function isSiteIdToken({ value }: {
22
+ value: string;
23
+ }, _optional?: {}): boolean;
24
+ export declare function createSiteKeySources(required: {
25
+ envName: string;
26
+ metadataFilename: string;
27
+ fields: {
28
+ siteId: string;
29
+ siteKeyId: string;
30
+ fingerprint: string;
31
+ };
32
+ localSegments: readonly string[];
33
+ sharedSegments: readonly string[];
34
+ volumeSegments: readonly string[];
35
+ legacyVolumeSegments: readonly string[];
36
+ assertHomeIsolation: (required: {
37
+ homeDir: string;
38
+ }) => void;
39
+ fs: {
40
+ existsSync(path: string): boolean;
41
+ readFileSync(path: string, encoding: "utf8"): string;
42
+ };
43
+ }, _optional?: {}): {
44
+ siteKeySources: (input: SiteKeySourcesInput, _optional?: {}) => SiteKeySource[];
45
+ resolveSiteKeyEnv: ({ env }: {
46
+ env: Record<string, string | undefined>;
47
+ }, _optional?: {}) => {
48
+ kind: "ok";
49
+ value: string;
50
+ varName: string;
51
+ } | {
52
+ kind: "absent";
53
+ };
54
+ readSiteMetaJson: ({ siteDir }: {
55
+ siteDir: string;
56
+ }, _optional?: {}) => Record<string, unknown> | undefined;
57
+ resolveSiteKeyId: (input: {
58
+ siteDir: string;
59
+ }, _optional?: {}) => string | undefined;
60
+ siteKeyEnvOnlySources: (_required?: {}, _optional?: {}) => SiteKeySource[];
61
+ readSiteMetaId: (input: {
62
+ siteDir: string;
63
+ }, _optional?: {}) => string | undefined;
64
+ siteKeySourcesForSiteDir(input: Omit<SiteKeySourcesInput, "siteKeyId"> & {
65
+ siteDir: string;
66
+ }, _optional?: {}): SiteKeySource[];
67
+ resolveSiteKeyFingerprint: (input: {
68
+ siteDir: string;
69
+ }, _optional?: {}) => string | undefined;
70
+ siteKeyFilePathFrom: ({ sources }: {
71
+ sources: readonly SiteKeySource[];
72
+ }, _optional?: {}) => string | undefined;
73
+ readSiteKeySourceMaterial: (input: {
74
+ source: SiteKeySource;
75
+ env: Record<string, string | undefined>;
76
+ }, _optional?: {}) => import("./material.js").SiteKeySourceMaterial | undefined;
77
+ };
78
+ export {};
79
+ //# sourceMappingURL=sources.d.ts.map
@@ -0,0 +1,119 @@
1
+ import { join } from "node:path";
2
+ import { readSiteMetaJson as readMeta, readSiteMetaId as readId, readSiteKeySourceMaterial as readMaterial } from "./material.js";
3
+ const SAFE_SITE_KEY_ID = /^[A-Za-z0-9._-]{1,128}$/;
4
+ /** Whether `id` can be used as a key-file name without escaping the configured site-key directory. */
5
+ export function isSafeSiteKeyId({ id }, _optional = {}) {
6
+ return SAFE_SITE_KEY_ID.test(id) && id !== "." && id !== "..";
7
+ }
8
+ const SITE_ID_TOKEN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
9
+ /**
10
+ * Whether a value may name a site: a UUID-like short token (letters, digits, `-`, `_`; at most 64).
11
+ * A site id travels into provider signals and, through the host's deployment configuration command, into a generated config
12
+ * file's env block, so a hand-edited or hostile `.site-meta.json` / the host's site-id env var (a newline, quotes,
13
+ * a path) is refused rather than carried.
14
+ * @complexity O(1) (bounded length).
15
+ */
16
+ export function isSiteIdToken({ value }, _optional = {}) {
17
+ return SITE_ID_TOKEN.test(value);
18
+ }
19
+ export function createSiteKeySources(required, _optional = {}) {
20
+ const readSiteMetaJson = ({ siteDir }, _optional = {}) => readMeta({ filePath: join(siteDir, required.metadataFilename), readFileSync: required.fs.readFileSync });
21
+ const resolveSiteKeyEnv = ({ env }, _optional = {}) => {
22
+ const value = env[required.envName]?.trim();
23
+ return value ? { kind: "ok", value, varName: required.envName } : { kind: "absent" };
24
+ };
25
+ const boundResolveSiteKeyId = (input, _optional = {}) => resolveSiteKeyId({ meta: readSiteMetaJson(input), fields: required.fields });
26
+ const sourcesFor = (input, _optional = {}) => siteKeySources({ input, config: required });
27
+ return {
28
+ siteKeySources: sourcesFor, resolveSiteKeyEnv, readSiteMetaJson, resolveSiteKeyId: boundResolveSiteKeyId,
29
+ siteKeyEnvOnlySources: (_required = {}, _optional = {}) => [{ kind: "env" }],
30
+ readSiteMetaId: (input, _optional = {}) => readId({ siteDir: input.siteDir, readSiteMetaJson, idField: required.fields.siteId, fallbackIdField: required.fields.siteKeyId }),
31
+ siteKeySourcesForSiteDir(input, _optional = {}) {
32
+ const siteKeyId = boundResolveSiteKeyId({ siteDir: input.siteDir });
33
+ return sourcesFor({ mode: input.mode, env: input.env, home: input.home, cwd: input.cwd, siteKeyId });
34
+ },
35
+ resolveSiteKeyFingerprint: (input, _optional = {}) => resolveSiteKeyFingerprint({ meta: readSiteMetaJson(input), field: required.fields.fingerprint }),
36
+ siteKeyFilePathFrom: ({ sources }, _optional = {}) => sources.find(source => source.kind === "per-site-file" || source.kind === "volume-file")?.path,
37
+ readSiteKeySourceMaterial: (input, _optional = {}) => readMaterial({ source: input.source, env: input.env, fs: required.fs, resolveSiteKeyEnv }),
38
+ };
39
+ }
40
+ /**
41
+ * The ordered list of places to look for this site's key. Order is significant — the FIRST source
42
+ * whose material resolves wins (site-key plan §A.2's "the per-site file wins over the env var").
43
+ *
44
+ * @complexity O(1) — a fixed-size list, no I/O.
45
+ */
46
+ function siteKeySources({ input, config }, _optional = {}) {
47
+ const envSource = { kind: "env" };
48
+ if (input.mode === "production") {
49
+ return [envSource, { kind: "volume-file", path: join(input.cwd, ...config.volumeSegments) }, { kind: "legacy-volume-file", path: legacyVolumeFilePath({ cwd: input.cwd, segments: config.legacyVolumeSegments }) }];
50
+ }
51
+ config.assertHomeIsolation({ homeDir: input.home });
52
+ const sources = [];
53
+ if (input.siteKeyId && isSafeSiteKeyId({ id: input.siteKeyId })) {
54
+ sources.push({ kind: "per-site-file", path: perSiteFilePath({ home: input.home, siteKeyId: input.siteKeyId, segments: config.localSegments }) });
55
+ }
56
+ sources.push(envSource);
57
+ sources.push({ kind: "legacy-shared-file", path: legacySharedFilePath({ home: input.home, segments: config.sharedSegments }) });
58
+ return sources;
59
+ }
60
+ /**
61
+ * This site's `siteKeyId` for {@link siteKeySources}, read straight from `.site-meta.json` — a
62
+ * READ-ONLY helper (unlike `site-key-ensure.ts`'s `ensureSiteKey`), safe for a route under
63
+ * `server/inbound/**` to import directly (site-key plan §A3a: nothing under that tree may import
64
+ * `site-key-ensure.ts`, the one WRITER — this module stays the reader both sides can share).
65
+ *
66
+ * Stage A4 (not built yet) is what writes a distinct `siteKeyId` field into `.site-meta.json`; until
67
+ * then every site's key is named after its `siteId` (A.1: "It defaults to siteId when missing"), so
68
+ * a present `siteKeyId` field wins when both exist (forward-compatible with A4's write) and `siteId`
69
+ * is the fallback otherwise.
70
+ *
71
+ * Never throws: a missing file, malformed JSON, or a non-string/empty field all resolve to
72
+ * `undefined` — exactly the input {@link siteKeySources} already treats as "no per-site candidate",
73
+ * so a site with no readable meta (a legacy or unrepaired install) falls back to its pre-site-key
74
+ * env/legacy-file-only behavior rather than crashing a boot or an admin request.
75
+ *
76
+ * @complexity O(1) — one small, bounded-size file read (via {@link readSiteMetaJson}).
77
+ */
78
+ function resolveSiteKeyId({ meta, fields }, _optional = {}) {
79
+ if (meta === undefined)
80
+ return undefined;
81
+ const keyId = meta[fields.siteKeyId];
82
+ const id = typeof keyId === "string" && keyId.length > 0 ? keyId : meta[fields.siteId];
83
+ // An unsafe id resolves to "no per-site key" (legacy readers only) rather than falling back to
84
+ // `siteId`: a site whose `siteKeyId` was tampered with must not quietly switch to another key file.
85
+ return typeof id === "string" && id.length > 0 && isSafeSiteKeyId({ id }) ? id : undefined;
86
+ }
87
+ /**
88
+ * This site's stamped `siteKeyFingerprint` from `.site-meta.json` (site-key plan §A.4/§A.6) — a
89
+ * READ-ONLY sibling of {@link resolveSiteKeyId}, same never-throws contract and same shared parse
90
+ * ({@link readSiteMetaJson}). Backs the admin site key route's `"mismatch"` state: a valid key
91
+ * resolving to a DIFFERENT fingerprint than this one means the physical key file was substituted
92
+ * after the stamp was written (`site-key-ensure.ts`'s `ensureSiteKey` derives the identical
93
+ * `"mismatch"` outcome for the write path from the same two values, via its own
94
+ * `withFingerprintReconciliation` — this function is the read-only counterpart for a caller, like
95
+ * the admin route, that must never write).
96
+ *
97
+ * @complexity O(1) — one small, bounded-size file read (via {@link readSiteMetaJson}).
98
+ */
99
+ function resolveSiteKeyFingerprint({ meta, field }, _optional = {}) {
100
+ if (meta === undefined)
101
+ return undefined;
102
+ const fingerprint = meta[field];
103
+ return typeof fingerprint === "string" && fingerprint.length > 0 ? fingerprint : undefined;
104
+ }
105
+ /** the configured per-site key path — A.1's per-site local path. */
106
+ function perSiteFilePath({ home, siteKeyId, segments }, _optional = {}) {
107
+ return join(home, ...segments, `${siteKeyId}.hex`);
108
+ }
109
+ /** the configured legacy shared key path — the one shared file every install had before per-site
110
+ * keys, still read (never written by a reader) as an adoption source. */
111
+ function legacySharedFilePath({ home, segments }, _optional = {}) {
112
+ return join(home, ...segments);
113
+ }
114
+ /** the configured legacy volume key path — the production durable-volume path
115
+ * (`keyring.env.ts`'s `defaultSiteKeyFilePath` production branch), reused here unchanged. */
116
+ function legacyVolumeFilePath({ cwd, segments }, _optional = {}) {
117
+ return join(cwd, ...segments);
118
+ }
119
+ //# sourceMappingURL=sources.js.map
@@ -1,5 +1,21 @@
1
1
  import type { KeyringPort, RootKeyHandle, SecretSealerPort } from "@jini-ai/core/contracts/vault";
2
2
  import type { SealedSecret } from "./types.js";
3
+ /**
4
+ * `code` on what {@link AesGcmSecretSealer.open} throws when the sealed value itself can't be opened:
5
+ * a wrong, lost or re-minted key (the GCM auth tag fails), a tampered or damaged envelope, an
6
+ * unsupported `alg`. Callers classify by this code, never by the message: the auth-tag failure's
7
+ * wording is the crypto runtime's own (OpenSSL in Node, BoringSSL in Electron) and may change. A
8
+ * keyring that can't derive at all (no key, an unusable key) is NOT this: its error passes through.
9
+ */
10
+ export declare const SECRET_OPEN_FAILED = "SECRET_OPEN_FAILED";
11
+ /** A sealed value that could not be opened ({@link SECRET_OPEN_FAILED}); the message is the cause's. */
12
+ export declare class SecretOpenError extends Error {
13
+ readonly code = "SECRET_OPEN_FAILED";
14
+ constructor(required: {
15
+ cause: unknown;
16
+ }, _optional?: Record<string, never>);
17
+ }
18
+ /** AES-256-GCM `SecretSealerPort` adapter over a `KeyringPort`; the key is re-derived on every call. */
3
19
  export declare class AesGcmSecretSealer implements SecretSealerPort {
4
20
  private readonly keyring;
5
21
  private readonly randomBytesFn;
@@ -11,13 +27,27 @@ export declare class AesGcmSecretSealer implements SecretSealerPort {
11
27
  byteLength: number;
12
28
  }) => Uint8Array;
13
29
  });
14
- /** Encrypts under the requested generation with a fresh IV; AAD must be reconstructed on open. */
30
+ /** Encrypts under the requested generation with a fresh IV; AAD must be reconstructed on open.
31
+ * @param input.aad - Required context bound into the GCM tag, never stored. An omitted or
32
+ * non-string `aad` is refused before any key derivation (no unbound write on this entry point).
33
+ * @returns `{keyId, ciphertext, nonce, alg}`; `ciphertext` is base64(ciphertext || 16-byte tag).
34
+ * @throws Whatever `KeyringPort.derive()` throws (e.g. a missing root key), never swallowed into a
35
+ * plaintext fallback; `TypeError` for a missing/non-string `aad` or a non-12-byte injected IV.
36
+ * @complexity O(plaintext bytes).
37
+ */
15
38
  seal(input: {
16
39
  plaintext: string;
17
40
  key: RootKeyHandle;
18
41
  aad: string;
19
42
  }): Promise<SealedSecret>;
20
- /** Opens under the envelope's generation. Wrong key, tag, nonce, or AAD fails authentication. */
43
+ /** Opens under the envelope's generation. Wrong key, tag, nonce, or AAD fails authentication.
44
+ * @param optional.aad - The byte-identical string the value was sealed with; omitted iff it was
45
+ * sealed with none. Any mismatch, in either direction, fails the auth tag.
46
+ * @throws {SecretOpenError} Unsupported `alg`, a malformed/short envelope, or a failed auth tag
47
+ * (wrong key, tampering, changed AAD), with the runtime's error kept as `cause`.
48
+ * @throws Whatever `KeyringPort.derive()` throws, as itself (an unconfigured store, not a bad row).
49
+ * @complexity O(ciphertext bytes).
50
+ */
21
51
  open(input: {
22
52
  sealed: SealedSecret;
23
53
  }, { aad }?: {
@@ -25,4 +55,22 @@ export declare class AesGcmSecretSealer implements SecretSealerPort {
25
55
  }): Promise<string>;
26
56
  private deriveAesKey;
27
57
  }
58
+ /**
59
+ * COMPATIBILITY binding: an {@link AesGcmSecretSealer} whose `seal` also accepts an omitted `aad`
60
+ * and writes the historical UNBOUND format (zero AAD bytes; byte-identical to `aad: ""` and to the
61
+ * pre-AAD implementation). Such a record is not tied to any row: it opens wherever no context is
62
+ * supplied. Only a host that must keep producing that format constructs this class, by name, at its
63
+ * composition root; every other caller uses the strict {@link AesGcmSecretSealer}. Opening is unchanged.
64
+ */
65
+ export declare class LegacyUnboundAesGcmSecretSealer extends AesGcmSecretSealer {
66
+ /** Seals like {@link AesGcmSecretSealer.seal}; an omitted `aad` (only `undefined`) becomes zero AAD bytes.
67
+ * @throws `TypeError` for a present non-string `aad` (e.g. `null`); otherwise as the strict `seal`.
68
+ * @complexity O(plaintext bytes).
69
+ */
70
+ seal(input: {
71
+ plaintext: string;
72
+ key: RootKeyHandle;
73
+ aad?: string;
74
+ }): Promise<SealedSecret>;
75
+ }
28
76
  //# sourceMappingURL=secret-sealer.aesgcm.d.ts.map