@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.
- package/CHANGELOG.md +7 -0
- package/README.md +13 -0
- package/dist/download-lock.d.ts +3 -1
- package/dist/download-lock.js +4 -6
- package/dist/download-maintenance.js +6 -6
- package/dist/download-state.js +17 -14
- package/dist/download-store.d.ts +34 -10
- package/dist/download-store.js +24 -20
- package/dist/download-target.d.ts +6 -2
- package/dist/download-target.js +7 -7
- package/dist/download-transfer.js +18 -12
- package/dist/download.js +4 -4
- package/dist/fetch-with-timeout.d.ts +0 -53
- package/dist/fetch-with-timeout.js +62 -13
- package/dist/fs/directory-running-lock.d.ts +4 -0
- package/dist/fs/directory-running-lock.js +8 -1
- package/dist/fs/directory-workspace.d.ts +2 -1
- package/dist/fs/directory-workspace.js +2 -2
- package/dist/fs/durable-json.d.ts +3 -16
- package/dist/fs/durable-json.js +4 -2
- package/dist/fs/guarded-reader.d.ts +10 -0
- package/dist/fs/guarded-reader.js +34 -1
- package/dist/fs/index.d.ts +4 -0
- package/dist/fs/index.js +4 -0
- package/dist/fs/leased-directory-move.d.ts +49 -0
- package/dist/fs/leased-directory-move.js +31 -0
- package/dist/fs/owned-temp-root.d.ts +74 -0
- package/dist/fs/owned-temp-root.js +203 -0
- package/dist/fs/recent-directories.d.ts +2 -1
- package/dist/fs/resolve-directory-target.d.ts +33 -0
- package/dist/fs/resolve-directory-target.js +58 -0
- package/dist/fs/staged-file.d.ts +40 -0
- package/dist/fs/staged-file.js +75 -0
- package/dist/fs/strict-containment.d.ts +14 -0
- package/dist/fs/strict-containment.js +14 -0
- package/dist/image/png-encode.d.ts +41 -0
- package/dist/image/png-encode.js +96 -0
- package/dist/index.d.ts +3 -1
- package/dist/mail/email-template-agent-tools.d.ts +150 -0
- package/dist/mail/email-template-agent-tools.js +86 -0
- package/dist/mail/email-template-tool-registrations.d.ts +73 -0
- package/dist/mail/email-template-tool-registrations.js +66 -0
- package/dist/mail/email-template.js +3 -7
- package/dist/mail/feedback-route.d.ts +50 -0
- package/dist/mail/feedback-route.js +46 -0
- package/dist/mail/feedback-setup.d.ts +44 -0
- package/dist/mail/feedback-setup.js +53 -0
- package/dist/mail/feedback-sources.d.ts +67 -0
- package/dist/mail/feedback-sources.js +42 -0
- package/dist/mail/index.d.ts +10 -1
- package/dist/mail/index.js +4 -0
- package/dist/mail/mail-status.d.ts +32 -0
- package/dist/mail/mail-status.js +2 -0
- package/dist/mail/positional-purpose-gate.d.ts +14 -0
- package/dist/mail/positional-purpose-gate.js +18 -0
- package/dist/mail/purpose-gate-probe.d.ts +18 -0
- package/dist/mail/purpose-gate-probe.js +22 -0
- package/dist/mail/purpose-scoped-mailer.d.ts +4 -0
- package/dist/mail/purpose-scoped-mailer.js +4 -3
- package/dist/mail/resolve-mailer.d.ts +13 -1
- package/dist/mail/resolve-mailer.js +11 -5
- package/dist/mail/sql/activity.repo.d.ts +20 -0
- package/dist/mail/sql/activity.repo.js +133 -0
- package/dist/mail/sql/attempts.repo.d.ts +17 -0
- package/dist/mail/sql/attempts.repo.js +32 -0
- package/dist/mail/sql/capture.repo.d.ts +69 -0
- package/dist/mail/sql/capture.repo.js +119 -0
- package/dist/mail/sql/feedback-inbox.repo.d.ts +12 -0
- package/dist/mail/sql/feedback-inbox.repo.js +32 -0
- package/dist/mail/sql/index.d.ts +12 -0
- package/dist/mail/sql/index.js +12 -0
- package/dist/mail/sql/ledger.repo.d.ts +29 -0
- package/dist/mail/sql/ledger.repo.js +57 -0
- package/dist/mail/sql/retention.d.ts +23 -0
- package/dist/mail/sql/retention.js +53 -0
- package/dist/mail/sql/site-feedback-route.d.ts +18 -0
- package/dist/mail/sql/site-feedback-route.js +22 -0
- package/dist/mail/sql/suppression-admin.repo.d.ts +11 -0
- package/dist/mail/sql/suppression-admin.repo.js +76 -0
- package/dist/mail/sql/suppression.repo.d.ts +10 -0
- package/dist/mail/sql/suppression.repo.js +33 -0
- package/dist/mail/test-send.d.ts +147 -0
- package/dist/mail/test-send.js +198 -0
- package/dist/mail/use-readiness.d.ts +104 -0
- package/dist/mail/use-readiness.js +140 -0
- package/dist/object-store/local-fs.js +34 -1
- package/dist/object-store/site/artifact-provider.d.ts +65 -0
- package/dist/object-store/site/artifact-provider.js +37 -0
- package/dist/object-store/site/registry.d.ts +110 -0
- package/dist/object-store/site/registry.js +93 -0
- package/dist/object-store/site/setting.d.ts +34 -0
- package/dist/object-store/site/setting.js +32 -0
- package/dist/process-probes.d.ts +11 -4
- package/dist/process-probes.js +3 -3
- package/dist/process-top-footprint.d.ts +1 -1
- package/dist/process-top-footprint.js +1 -3
- package/dist/process.d.ts +3 -17
- package/dist/process.js +3 -2
- package/dist/retention/index.d.ts +6 -0
- package/dist/retention/index.js +6 -0
- package/dist/retention/measure-tree.d.ts +68 -0
- package/dist/retention/measure-tree.js +205 -0
- package/dist/retention/preview-store.d.ts +12 -0
- package/dist/retention/preview-store.js +28 -0
- package/dist/retention/routes.d.ts +23 -0
- package/dist/retention/routes.js +24 -0
- package/dist/retention/runner.d.ts +103 -0
- package/dist/retention/runner.js +164 -0
- package/dist/secrets/credential-sets/index.d.ts +1 -0
- package/dist/secrets/credential-sets/index.js +1 -0
- package/dist/secrets/credential-sets/store-vault-guards.d.ts +26 -0
- package/dist/secrets/credential-sets/store-vault-guards.js +30 -0
- package/dist/secrets/credential-sets/vault.service.d.ts +1 -1
- package/dist/secrets/index.d.ts +1 -1
- package/dist/secrets/index.js +1 -1
- package/dist/secrets/keyring.env.d.ts +1 -1
- package/dist/secrets/keyring.env.js +3 -5
- package/dist/secrets/keyring.memory.d.ts +4 -1
- package/dist/secrets/keyring.memory.js +4 -1
- package/dist/secrets/legacy-codecs.d.ts +381 -0
- package/dist/secrets/legacy-codecs.js +468 -0
- package/dist/secrets/legacy-owner.d.ts +3 -11
- package/dist/secrets/root-key/ensure.d.ts +154 -0
- package/dist/secrets/root-key/ensure.js +328 -0
- package/dist/secrets/root-key/files.d.ts +104 -0
- package/dist/secrets/root-key/files.js +166 -0
- package/dist/secrets/root-key/material.d.ts +132 -0
- package/dist/secrets/root-key/material.js +116 -0
- package/dist/secrets/root-key/ordered-keyring.d.ts +157 -0
- package/dist/secrets/root-key/ordered-keyring.js +104 -0
- package/dist/secrets/root-key/reconcile.d.ts +50 -0
- package/dist/secrets/root-key/reconcile.js +147 -0
- package/dist/secrets/root-key/site-keyring-errors.d.ts +78 -0
- package/dist/secrets/root-key/site-keyring-errors.js +37 -0
- package/dist/secrets/root-key/sources.d.ts +79 -0
- package/dist/secrets/root-key/sources.js +119 -0
- package/dist/secrets/secret-sealer.aesgcm.d.ts +50 -2
- package/dist/secrets/secret-sealer.aesgcm.js +107 -19
- package/dist/web/tool-registrations.d.ts +67 -0
- package/dist/web/tool-registrations.js +44 -0
- package/package.json +138 -6
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import { reconcileRootKey } from "./reconcile.js";
|
|
2
|
+
import { atomicCreateSiteKeyFile as atomicCreate, moveSiteKeyFileAside as moveAside, installSiteKey as install } from "./files.js";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
/**
|
|
5
|
+
* @file Site-key plan (`ADS-memory/.local-artifacts/plan-site-key-2026-09-24.md`) §A.2 — the ONE
|
|
6
|
+
* writer for a site's key file. The CLI's old `host site-key ensure` command
|
|
7
|
+
* (`cli/commands/site-key.ts`) was absorbed into {@link ensureSiteKeyForBoot} and deleted outright
|
|
8
|
+
* (Stage A3b, `abc4807d5`) — `planSiteKeyEnsure`/`SiteKeyEnsurePlan` (that command's own pure
|
|
9
|
+
* decision table) went with it as dead code (site-key plan §A.6: zero callers once the CLI command
|
|
10
|
+
* was gone). `findSiteKeyDependentData` (the per-site scan `ensureSiteKey` uses, on every storage
|
|
11
|
+
* kind) lives in the host's dependent-data reader on the storage kernel; the admin site key
|
|
12
|
+
* route imports it there, and the boot callers inject it here ({@link KeyDependentDataScan}), so
|
|
13
|
+
* this feature never value-imports the host storage kernel.
|
|
14
|
+
*
|
|
15
|
+
* Purpose:
|
|
16
|
+
* `ensureSiteKey` runs once per server boot, local mode only (A.2): a per-site file already there
|
|
17
|
+
* and valid is a no-op; missing with an env/legacy-file key already in effect ADOPTS that exact
|
|
18
|
+
* material into the per-site file (never re-keys, never orphans); missing with nothing anywhere
|
|
19
|
+
* and no key-dependent data yet MINTS a fresh one; missing with key-dependent data already sealed
|
|
20
|
+
* REFUSES rather than silently starting a new key nothing can decrypt with. Production is always a
|
|
21
|
+
* no-op — it never had a per-site file to begin with (A.1's "why per-site rather than one key per
|
|
22
|
+
* OS user"; A.3's "production never mints").
|
|
23
|
+
*
|
|
24
|
+
* The write itself is race-safe with no single-instance lock (A.2's "atomic write, safe with many
|
|
25
|
+
* instances running at once"): a temp file is written and fsynced, then linked onto the final
|
|
26
|
+
* path — `link(2)` refuses `EEXIST` atomically, so at most one process's bytes ever become the
|
|
27
|
+
* file. Both the winner and every loser then read the FINAL file back rather than trusting their
|
|
28
|
+
* own in-memory candidate, so two instances racing (one adopting, one minting) always converge on
|
|
29
|
+
* the same key — see {@link atomicCreateSiteKeyFile}.
|
|
30
|
+
*
|
|
31
|
+
* Architectural role:
|
|
32
|
+
* Configured domain writer. Depends on `keyring.env.ts` (shared hex validator and
|
|
33
|
+
* fingerprint) and `site-key-sources.ts` (candidate ordering) — never the reverse: both keyrings
|
|
34
|
+
* stay readers (`allowFileAutoGenerate: false`), and this module is the only place `randomBytes`
|
|
35
|
+
* feeds a site key file. Nothing under `server/inbound/**` may import this module (site-key plan
|
|
36
|
+
* §A.3) — Stage A3a's own wiring test enforces that; this file does not import anything from
|
|
37
|
+
* `server/inbound` in either direction. The one request path that runs it, the admin site key
|
|
38
|
+
* `generate` (2026-09-29), receives {@link ensureSiteKeyForSite} from the composition root, so a
|
|
39
|
+
* request writes a key only by these same rules and never by a writer of its own.
|
|
40
|
+
*/
|
|
41
|
+
// ---------------------------------------------------------------------------
|
|
42
|
+
// ensureSiteKey — the per-site decision table and its one writer.
|
|
43
|
+
// ---------------------------------------------------------------------------
|
|
44
|
+
export function createSiteKeyEnsurer(required, _optional = {}) {
|
|
45
|
+
return {
|
|
46
|
+
ensureSiteKey: (input, _optional = {}) => ensureSiteKey({ input, config: required }),
|
|
47
|
+
ensureSiteKeyForBoot: (input, _optional = {}) => ensureSiteKeyForBoot({ input, config: required }),
|
|
48
|
+
ensureSiteKeyForSite: (input, _optional = {}) => ensureSiteKeyForSite({ input, config: required }),
|
|
49
|
+
mintSiteKeyHex: (_required = {}, _optional = {}) => mintSiteKeyHex(required),
|
|
50
|
+
installSiteKey: (input, _optional = {}) => installSiteKey({ input, config: required }),
|
|
51
|
+
atomicCreateSiteKeyFile: (input, _optional = {}) => atomicCreateSiteKeyFile({ ...input, config: required }),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The only writer of a site's key file (site-key plan §A.2). Safe to call on every boot: a valid
|
|
56
|
+
* existing file is read, not rewritten, and the two write-producing outcomes (`"adopt"`, `"mint"`)
|
|
57
|
+
* both go through {@link atomicCreateSiteKeyFile}'s race-safe create. A per-site file the stamp does
|
|
58
|
+
* not name is replaced only when another source holds the stamped key, and is moved aside as a
|
|
59
|
+
* backup first ({@link moveSiteKeyFileAside}), never deleted.
|
|
60
|
+
*
|
|
61
|
+
* @throws whatever the underlying `fs` calls throw for a path that exists but cannot be read
|
|
62
|
+
* (permissions, a torn file) — this function never swallows those into a wrong decision. The
|
|
63
|
+
* injected scan fails closed on an unreadable database instead of throwing.
|
|
64
|
+
* @complexity O(1) fs/env reads plus the injected scan's cost, and only on the branches that need it.
|
|
65
|
+
*/
|
|
66
|
+
async function ensureSiteKey({ input, config }, _optional = {}) {
|
|
67
|
+
const env = input.env ?? config.env();
|
|
68
|
+
const mode = input.mode ?? config.resolveRuntimeMode({ env });
|
|
69
|
+
if (mode === "production") {
|
|
70
|
+
return { action: "production-noop" };
|
|
71
|
+
}
|
|
72
|
+
const { perSiteSource, otherSources } = splitPerSiteSource({ input, mode, env, config });
|
|
73
|
+
const perSiteFilePath = perSiteSource.path;
|
|
74
|
+
const result = await reconcileRootKey({ ports: {
|
|
75
|
+
readPerSite: () => readRawSiteKeyMaterial({ source: perSiteSource, env, config }),
|
|
76
|
+
get stampedFingerprint() { return config.resolveSiteKeyFingerprint({ siteDir: input.siteDir }); },
|
|
77
|
+
others: otherSources.map(source => () => readRawSiteKeyMaterial({ source, env, config })),
|
|
78
|
+
hasDependentData: () => config.findSiteKeyDependentData({ siteDir: input.siteDir }),
|
|
79
|
+
moveAside: ({ expectedContent }) => { moveSiteKeyFileAside({ filePath: perSiteFilePath, expectedContent, config }); },
|
|
80
|
+
createExclusive: ({ hex }) => atomicCreateSiteKeyFile({ filePath: perSiteFilePath, hex, config }),
|
|
81
|
+
mint: () => mintSiteKeyHex(config),
|
|
82
|
+
readStamp: () => {
|
|
83
|
+
const meta = config.readSiteMetaJson({ siteDir: input.siteDir });
|
|
84
|
+
if (meta === undefined)
|
|
85
|
+
return { kind: "no-meta" };
|
|
86
|
+
return { kind: "meta", fingerprint: meta[config.fields.fingerprint],
|
|
87
|
+
write: ({ fingerprint }) => writeFingerprintStamp({ siteDir: input.siteDir, meta, fingerprint, config }), };
|
|
88
|
+
},
|
|
89
|
+
} });
|
|
90
|
+
return { action: result.action, perSiteFilePath, ...("reason" in result ? { reason: result.reason } : {}), ...("fingerprint" in result ? { fingerprint: result.fingerprint } : {}) };
|
|
91
|
+
}
|
|
92
|
+
/** `siteKeySources` for this site, split into its per-site file and every OTHER source.
|
|
93
|
+
* @throws {Error} No per-site candidate — `siteKeySources` drops it for an unsafe `siteKeyId`. */
|
|
94
|
+
function splitPerSiteSource(required) {
|
|
95
|
+
const { input, mode, env, config } = required;
|
|
96
|
+
const home = input.home ?? config.home();
|
|
97
|
+
const cwd = input.cwd ?? config.cwd();
|
|
98
|
+
const sources = config.siteKeySources({ mode, env, home, cwd, siteKeyId: input.siteKeyId });
|
|
99
|
+
const perSiteSource = sources.find((source) => source.kind === "per-site-file");
|
|
100
|
+
if (!perSiteSource) {
|
|
101
|
+
// Invariant guard, not a real runtime branch: `siteKeyId` is always passed above, and
|
|
102
|
+
// `siteKeySources` always includes a per-site candidate when one is given.
|
|
103
|
+
throw new Error("ensureSiteKey: siteKeySources did not return a per-site-file candidate for a given siteKeyId");
|
|
104
|
+
}
|
|
105
|
+
return { perSiteSource, otherSources: sources.filter((source) => source.kind !== "per-site-file") };
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Site-key plan §A3a's actual boot-path call site: the host boot entry points call
|
|
109
|
+
* this, not {@link ensureSiteKey} directly, so neither has to resolve `siteKeyId` itself. Resolves it
|
|
110
|
+
* from `siteDir`'s own `.site-meta.json` via {@link resolveSiteKeyId} and, only when that succeeds,
|
|
111
|
+
* calls through to {@link ensureSiteKey}.
|
|
112
|
+
*
|
|
113
|
+
* A `siteDir` with NO `.site-meta.json` at all is not a hypothetical: the default `sites/<name>/`
|
|
114
|
+
* directory `index.ts` boots (`npm start`/`npm run dev`) is deliberately never given one — it is not
|
|
115
|
+
* a `host init`/`host serve <dir>` install directory (`content-db-schema-guard.ts`'s own header).
|
|
116
|
+
* Before this fix that meant exactly that site's key was silently never ensured — no error, no log
|
|
117
|
+
* line, and every later admin request just quietly found no key. Local mode now closes that gap
|
|
118
|
+
* itself: an ABSENT `.site-meta.json` gets a brand-new one ({@link
|
|
119
|
+
* mintMinimalSiteMetaJson}) carrying a fresh `siteKeyId` — complete when the db already has
|
|
120
|
+
* migrations to derive a schema stamp from, key-only otherwise ({@link mintSiteMetaForBootIfAbsent})
|
|
121
|
+
* — then boot proceeds exactly as it would have for a site that already had one. Production never does this (A.1/A.3: production
|
|
122
|
+
* never mints a site identity any more than it mints a key) — a `siteDir` with no meta file in
|
|
123
|
+
* production keeps its pre-site-key env/legacy-file-only behavior, exactly as before this feature
|
|
124
|
+
* existed. A `.site-meta.json` that EXISTS but cannot be parsed (corrupt, oversized, not an object)
|
|
125
|
+
* is a different case — {@link resolveSiteKeyId} already treats that as "no per-site candidate", and
|
|
126
|
+
* this function must never paper over a corrupt file by replacing it with a fresh one; only a
|
|
127
|
+
* genuinely absent file is ever minted (see {@link mintMinimalSiteMetaJson}'s own exclusive-create
|
|
128
|
+
* guard).
|
|
129
|
+
*
|
|
130
|
+
* The whole boot-time attempt — minting the meta file, and {@link ensureSiteKey}'s own key-file
|
|
131
|
+
* write — is wrapped in one try/catch (2026-09-24 fix): a boot whose the host home directory (or equivalent) cannot
|
|
132
|
+
* be written must still start the server. `ensureSiteKey` itself deliberately keeps its own
|
|
133
|
+
* never-swallow contract (its own `@throws` doc) for a caller that wants to fail loudly; this
|
|
134
|
+
* function is the boot-path wrapper specifically, and a boot-time key failure is exactly the class
|
|
135
|
+
* of thing `site-key-boot-notice.ts` exists to surface at the terminal, not crash the process over —
|
|
136
|
+
* the admin status route already reports a missing key the same way it does for any other reason one
|
|
137
|
+
* was never created.
|
|
138
|
+
*
|
|
139
|
+
* @throws never — every failure below (meta-mint or the underlying `ensureSiteKey` write) is caught,
|
|
140
|
+
* logged once, and reported as `undefined`, the same "nothing to give a caller" result as a siteDir
|
|
141
|
+
* with no resolvable `siteKeyId` at all.
|
|
142
|
+
* @complexity O(1) fs read for `resolveSiteKeyId`, plus at most one more small fs write
|
|
143
|
+
* ({@link mintMinimalSiteMetaJson}), plus {@link ensureSiteKey}'s own cost when it runs.
|
|
144
|
+
*/
|
|
145
|
+
async function ensureSiteKeyForBoot({ input, config }, _optional = {}) {
|
|
146
|
+
try {
|
|
147
|
+
return await ensureSiteKeyForSite({ input, config });
|
|
148
|
+
}
|
|
149
|
+
catch (err) {
|
|
150
|
+
// Boot must never go down over this — see this function's own header. `console.error` (not the
|
|
151
|
+
// `warn`-level line `site-key-boot-notice.ts` prints moments later on the same terminal) so an
|
|
152
|
+
// operator can tell "the key mechanism itself failed" apart from "no key happens to exist yet".
|
|
153
|
+
config.logBootError({ siteDir: input.siteDir, error: err });
|
|
154
|
+
return undefined;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* {@link ensureSiteKeyForBoot} without its catch: resolves (or, in local mode, mints) this site's
|
|
159
|
+
* `siteKeyId`, then runs {@link ensureSiteKey}. Also the admin site key route's `generate`, injected
|
|
160
|
+
* by the composition root (the host composition root) so that route mints, adopts and
|
|
161
|
+
* refuses by exactly the rules boot uses rather than a second writer of its own.
|
|
162
|
+
*
|
|
163
|
+
* @returns `undefined` when no `siteKeyId` resolves (production with no meta file, or a meta file
|
|
164
|
+
* that exists but is unreadable).
|
|
165
|
+
* @throws whatever {@link ensureSiteKey} or the meta-file mint throws.
|
|
166
|
+
* @complexity Same as {@link ensureSiteKeyForBoot}.
|
|
167
|
+
*/
|
|
168
|
+
async function ensureSiteKeyForSite({ input, config }, _optional = {}) {
|
|
169
|
+
const env = input.env ?? config.env();
|
|
170
|
+
const mode = input.mode ?? config.resolveRuntimeMode({ env });
|
|
171
|
+
const siteKeyId = config.resolveSiteKeyId({ siteDir: input.siteDir }) ?? (await mintSiteMetaForBootIfAbsent({ siteDir: input.siteDir, mode, config }));
|
|
172
|
+
if (!siteKeyId)
|
|
173
|
+
return undefined;
|
|
174
|
+
return ensureSiteKey({ input: {
|
|
175
|
+
siteDir: input.siteDir,
|
|
176
|
+
siteKeyId,
|
|
177
|
+
mode,
|
|
178
|
+
env,
|
|
179
|
+
home: input.home,
|
|
180
|
+
cwd: input.cwd,
|
|
181
|
+
}, config });
|
|
182
|
+
}
|
|
183
|
+
/** A fresh 32-byte site key as 64 hex characters — the key "Start fresh" installs when no working
|
|
184
|
+
* key is present. Lives here so this module stays the one place a site key is generated.
|
|
185
|
+
* @complexity O(1). */
|
|
186
|
+
function mintSiteKeyHex(config, _optional = {}) {
|
|
187
|
+
return config.randomBytes(32).toString("hex");
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Makes `hex` this site's key — the site key tab's recovery writer (design §4.3/§4.6: "Unlock
|
|
191
|
+
* with token", "Start fresh"). The caller has already decided `hex` is right; this only writes it.
|
|
192
|
+
*
|
|
193
|
+
* The target is the first key file in this site's source order (the per-site file locally, the
|
|
194
|
+
* durable-volume file in production). An env var ahead of it that holds a different key would
|
|
195
|
+
* outrank any file, so that is refused (`env-key-set`); one holding `hex` already is fine. A target
|
|
196
|
+
* file holding a different key (or garbage) is moved aside as a backup, never deleted. Then
|
|
197
|
+
* `.site-meta.json`'s `siteKeyFingerprint` is set to `hex`'s (other fields kept; a missing meta
|
|
198
|
+
* file is minted locally, left alone in production).
|
|
199
|
+
*
|
|
200
|
+
* @returns `undefined` when no `siteKeyId` resolves in local mode (an unreadable meta file).
|
|
201
|
+
* @throws {Error} `hex` is not a valid key (nothing written), or the file ends up holding another
|
|
202
|
+
* key (a concurrent writer won the race), or whatever `fs` throws.
|
|
203
|
+
* @complexity O(n) in the (fixed-size) source list, plus a few small file reads/writes.
|
|
204
|
+
*/
|
|
205
|
+
function installSiteKey({ input, config }, _optional = {}) {
|
|
206
|
+
return install({ ...input, resolveInstallSources: () => resolveInstallSources({ input, config }), readSiteKeySourceMaterial: config.readSiteKeySourceMaterial,
|
|
207
|
+
moveSiteKeyFileAside: request => moveSiteKeyFileAside({ ...request, config }), atomicCreateSiteKeyFile: request => atomicCreateSiteKeyFile({ ...request, config }), stampFingerprint: request => stampFingerprint({ ...request, config }),
|
|
208
|
+
invalidKeyError: reason => new Error(`installSiteKey: not a valid site key (${reason})`),
|
|
209
|
+
noFileError: () => new Error("installSiteKey: this site has no key file to write"),
|
|
210
|
+
concurrentWriteError: () => new Error("installSiteKey: another process wrote a different key at the same moment; nothing was stamped"),
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
/** This site's ordered sources for {@link installSiteKey} (a missing local meta file is minted), or
|
|
214
|
+
* `undefined` when no `siteKeyId` resolves in local mode. */
|
|
215
|
+
function resolveInstallSources({ input, config }, _optional = {}) {
|
|
216
|
+
const env = input.env ?? config.env();
|
|
217
|
+
const mode = input.mode ?? config.resolveRuntimeMode({ env });
|
|
218
|
+
const siteKeyId = config.resolveSiteKeyId({ siteDir: input.siteDir }) ?? mintSiteKeyIdIfAbsent({ siteDir: input.siteDir, mode, config });
|
|
219
|
+
if (mode !== "production" && !siteKeyId)
|
|
220
|
+
return undefined;
|
|
221
|
+
return { env, sources: config.siteKeySources({ mode, env, home: input.home ?? config.home(), cwd: input.cwd ?? config.cwd(), siteKeyId }) };
|
|
222
|
+
}
|
|
223
|
+
function stampFingerprint({ siteDir, fingerprint, config }, _optional = {}) {
|
|
224
|
+
const meta = config.readSiteMetaJson({ siteDir });
|
|
225
|
+
if (meta === undefined || meta[config.fields.fingerprint] === fingerprint)
|
|
226
|
+
return;
|
|
227
|
+
writeFingerprintStamp({ siteDir, meta, fingerprint, config });
|
|
228
|
+
}
|
|
229
|
+
/** Writes `meta` back with `siteKeyFingerprint` set — atomically, every other field kept. */
|
|
230
|
+
function writeFingerprintStamp({ siteDir, meta, fingerprint, config }, _optional = {}) {
|
|
231
|
+
config.writeJsonFileAtomic({ filePath: join(siteDir, config.metadataFilename), data: { ...meta, [config.fields.fingerprint]: fingerprint } });
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* `.site-meta.json` has no `siteKeyId` (or `siteId`) to resolve at all — for local mode only, mints
|
|
235
|
+
* a brand-new, minimal `.site-meta.json` carrying just a fresh `siteKeyId`, and returns it. Never
|
|
236
|
+
* called in production (checked by the caller before reaching this function) and never touches a
|
|
237
|
+
* `siteDir` whose `.site-meta.json` already exists in ANY form, parseable or not — see
|
|
238
|
+
* {@link mintMinimalSiteMetaJson}'s own doc for why.
|
|
239
|
+
*
|
|
240
|
+
* @complexity O(1) — one `randomUUID`, one attempted exclusive file create.
|
|
241
|
+
*/
|
|
242
|
+
function mintSiteKeyIdIfAbsent({ siteDir, mode, config }, _optional = {}) {
|
|
243
|
+
if (mode === "production")
|
|
244
|
+
return undefined;
|
|
245
|
+
const siteKeyId = config.randomUUID();
|
|
246
|
+
return mintMinimalSiteMetaJson({ siteDir, siteKeyId, content: { [config.fields.siteKeyId]: siteKeyId }, config });
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* {@link mintSiteKeyIdIfAbsent} for the boot path, which can wait on a db read: when the site's
|
|
250
|
+
* `content.db` already has migrations applied, the minted file is a COMPLETE `.site-meta.json`
|
|
251
|
+
* (`buildSiteMetaForNewKey` — schema stamp derived from the db, `siteId` = the fresh `siteKeyId`), so
|
|
252
|
+
* `host serve`/the desktop accept the folder straight away. With no migrated db yet (a brand-new dev
|
|
253
|
+
* site: the composition creates it after this runs) it falls back to the key-only shape, because
|
|
254
|
+
* minting nothing would leave this boot without a site key; the dev boot completes that file once
|
|
255
|
+
* the db is migrated (the host boot entry point).
|
|
256
|
+
*
|
|
257
|
+
* @complexity O(m) in the bundled journal's entry count (one read-only db open), plus one exclusive
|
|
258
|
+
* file create.
|
|
259
|
+
*/
|
|
260
|
+
async function mintSiteMetaForBootIfAbsent({ siteDir, mode, config }, _optional = {}) {
|
|
261
|
+
if (mode === "production")
|
|
262
|
+
return undefined;
|
|
263
|
+
const siteKeyId = config.randomUUID();
|
|
264
|
+
const complete = await config.buildSiteMetaForNewKey({ dir: siteDir, siteKeyId });
|
|
265
|
+
return mintMinimalSiteMetaJson({ siteDir, siteKeyId, content: complete ?? { [config.fields.siteKeyId]: siteKeyId }, config });
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Creates `<siteDir>/.site-meta.json` holding `content` — either just the fresh `siteKeyId`, or the
|
|
269
|
+
* complete meta {@link mintSiteMetaForBootIfAbsent} derived for it — EXCLUSIVELY (`flag:
|
|
270
|
+
* "wx"` — fails atomically with `EEXIST` if anything is already there) — race-safe the same way
|
|
271
|
+
* {@link atomicCreateSiteKeyFile} is, and for the identical reason (site-key plan §A.2's "no
|
|
272
|
+
* single-instance lock": this owner runs many local instances of the same site at once). Never
|
|
273
|
+
* overwrites, never merges into, never repairs an existing file, however corrupt or incomplete —
|
|
274
|
+
* "preserve anything present" means exactly that: the moment ANY `.site-meta.json` exists at
|
|
275
|
+
* `siteDir`, this function's job is already done (or was never its job at all), and it must not
|
|
276
|
+
* guess at what a caller who wrote that file intended.
|
|
277
|
+
*
|
|
278
|
+
* On `EEXIST` (this call lost a boot race against another instance, or — vanishingly unlikely given
|
|
279
|
+
* the caller already checked — a file appeared between that check and this write) reads back
|
|
280
|
+
* whatever is now on disk via {@link resolveSiteKeyId} rather than trusting its own candidate,
|
|
281
|
+
* exactly the "both winner and loser converge on the same reality" rule {@link
|
|
282
|
+
* atomicCreateSiteKeyFile} documents for the key file itself. That real file may turn out to have no
|
|
283
|
+
* resolvable id at all (e.g. the winner's own write raced a THIRD process that got there first with
|
|
284
|
+
* a corrupt file) — this function reports that honestly as `undefined` rather than minting a SECOND
|
|
285
|
+
* file the first write already made unnecessary.
|
|
286
|
+
*
|
|
287
|
+
* The file is key-only because this runs before the db is opened, so no schema stamp can be
|
|
288
|
+
* derived yet. It does not stay that way: the boot completes it once the db is migrated
|
|
289
|
+
* (the host's key-only metadata completion, called from its boot entry points), keeping
|
|
290
|
+
* the `siteKeyId` minted here.
|
|
291
|
+
*
|
|
292
|
+
* @returns the minted (or, on a lost race, the already-present) `siteKeyId`, or `undefined` when
|
|
293
|
+
* neither this call's own write nor a re-read of an existing file resolves to one.
|
|
294
|
+
* @throws whatever `writeFileSync` throws other than `EEXIST` (permissions, a missing/non-directory
|
|
295
|
+
* parent, disk full) — this function does not itself decide what a write failure means; its one
|
|
296
|
+
* caller, {@link ensureSiteKeyForBoot}, is the boot-time safety net that catches it.
|
|
297
|
+
* @complexity O(1) — one `randomUUID`, one attempted exclusive file write.
|
|
298
|
+
*/
|
|
299
|
+
function mintMinimalSiteMetaJson({ siteDir, siteKeyId, content, config }, _optional = {}) {
|
|
300
|
+
const metaPath = join(siteDir, config.metadataFilename);
|
|
301
|
+
try {
|
|
302
|
+
config.fs.writeFileSync(metaPath, JSON.stringify(content, null, 2), { flag: "wx", mode: config.fileMode });
|
|
303
|
+
return siteKeyId;
|
|
304
|
+
}
|
|
305
|
+
catch (err) {
|
|
306
|
+
if (!isErrorCode({ err, code: "EEXIST" }))
|
|
307
|
+
throw err;
|
|
308
|
+
return config.resolveSiteKeyId({ siteDir });
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
/** {@link decideLocalSiteKeyEnsure}'s input from a raw {@link parseSiteKeyHex} result (or
|
|
312
|
+
* `undefined` for "nothing there"). */
|
|
313
|
+
function moveSiteKeyFileAside(required, _optional = {}) {
|
|
314
|
+
return moveAside({ ...required, fs: required.config.fs, nowIso: required.config.nowIso, randomHex: ({ bytes }) => required.config.randomBytes(bytes).toString("hex"), fileMode: required.config.fileMode });
|
|
315
|
+
}
|
|
316
|
+
function atomicCreateSiteKeyFile(required, _optional = {}) {
|
|
317
|
+
return atomicCreate({ ...required, fs: required.config.fs,
|
|
318
|
+
pid: required.config.pid, randomHex: ({ bytes }) => required.config.randomBytes(bytes).toString("hex"), directoryMode: required.config.directoryMode, fileMode: required.config.fileMode });
|
|
319
|
+
}
|
|
320
|
+
function isErrorCode({ err, code }, _optional = {}) {
|
|
321
|
+
if (typeof err !== "object" || err === null || !("code" in err))
|
|
322
|
+
return false;
|
|
323
|
+
return err.code === code;
|
|
324
|
+
}
|
|
325
|
+
function readRawSiteKeyMaterial({ source, env, config }, _optional = {}) {
|
|
326
|
+
return config.readSiteKeySourceMaterial({ source, env })?.raw;
|
|
327
|
+
}
|
|
328
|
+
//# sourceMappingURL=ensure.js.map
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { type RootKeyRejection } from "../keyring.env.js";
|
|
2
|
+
import type { SiteKeySource, SiteKeySourceMaterial } from "./material.js";
|
|
3
|
+
/**
|
|
4
|
+
* Renames a wrong site key file to `<name>.wrong-<timestamp>` beside it (`0600`) so a key is never
|
|
5
|
+
* lost, even one that turned out to be the wrong one. Only moves the file when it still holds
|
|
6
|
+
* `expectedContent`: another instance that already replaced it must not have its fix moved aside.
|
|
7
|
+
* A file already gone (another instance moved it first) is not an error.
|
|
8
|
+
*
|
|
9
|
+
* @returns the backup path, or `undefined` when nothing was moved.
|
|
10
|
+
* @throws whatever `fs` throws other than `ENOENT`.
|
|
11
|
+
* @complexity O(1) — one read, one rename, one chmod.
|
|
12
|
+
*/
|
|
13
|
+
export declare function moveSiteKeyFileAside({ filePath, expectedContent, fs, nowIso, randomHex, fileMode }: {
|
|
14
|
+
filePath: string;
|
|
15
|
+
expectedContent: string;
|
|
16
|
+
fs: Pick<typeof import("node:fs"), "readFileSync" | "renameSync" | "chmodSync">;
|
|
17
|
+
nowIso: () => string;
|
|
18
|
+
randomHex: (required: {
|
|
19
|
+
bytes: number;
|
|
20
|
+
}) => string;
|
|
21
|
+
fileMode: number;
|
|
22
|
+
}, _optional?: {}): string | undefined;
|
|
23
|
+
/**
|
|
24
|
+
* Writes `hex` to `filePath`, race-safe with no single-instance lock (site-key plan §A.2): write a
|
|
25
|
+
* temp file in the same directory (`0600`, fsynced), then `linkSync` it onto `filePath` — `link(2)`
|
|
26
|
+
* fails atomically with `EEXIST` if anything is already there, so at most one process's bytes ever
|
|
27
|
+
* become the file. The loser's temp file is still removed; its `EEXIST` is swallowed, not
|
|
28
|
+
* propagated. Both the winner and every loser then read `filePath` back and return THAT (never
|
|
29
|
+
* their own `hex` argument), so two instances racing on the same `siteKeyId` always converge on
|
|
30
|
+
* the one file that won, whichever process actually wrote it. Also the project key's publisher
|
|
31
|
+
* (`server/runtime/composition/project-store.ts`), for the same race (web + desktop first start).
|
|
32
|
+
*
|
|
33
|
+
* @param required.filePath - the target `~/.host/site-keys/<id>.hex`. Its containing directory is created
|
|
34
|
+
* (`0700`) if missing.
|
|
35
|
+
* @param required.hex - this call's own candidate key material, used only if no one else wins the race.
|
|
36
|
+
* @returns the final file's content (trimmed) — always read from disk, never `hex` verbatim.
|
|
37
|
+
* @throws whatever `fs` throws other than `EEXIST` from the `linkSync` step.
|
|
38
|
+
* @complexity O(1) — a fixed number of syscalls, independent of `hex`'s length.
|
|
39
|
+
*/
|
|
40
|
+
export declare function atomicCreateSiteKeyFile({ filePath, hex, fs, pid, randomHex, directoryMode, fileMode }: {
|
|
41
|
+
filePath: string;
|
|
42
|
+
hex: string;
|
|
43
|
+
fs: Pick<typeof import("node:fs"), "mkdirSync" | "openSync" | "writeSync" | "fsyncSync" | "closeSync" | "chmodSync" | "linkSync" | "unlinkSync" | "readFileSync">;
|
|
44
|
+
pid: number;
|
|
45
|
+
randomHex: (required: {
|
|
46
|
+
bytes: number;
|
|
47
|
+
}) => string;
|
|
48
|
+
directoryMode: number;
|
|
49
|
+
fileMode: number;
|
|
50
|
+
}, _optional?: {}): string;
|
|
51
|
+
export interface InstallSiteKeyInput {
|
|
52
|
+
readonly siteDir: string;
|
|
53
|
+
readonly hex: string;
|
|
54
|
+
readonly resolveInstallSources: (input: InstallSiteKeyInput) => {
|
|
55
|
+
env: Record<string, string | undefined>;
|
|
56
|
+
sources: SiteKeySource[];
|
|
57
|
+
} | undefined;
|
|
58
|
+
readonly readSiteKeySourceMaterial: (required: {
|
|
59
|
+
source: SiteKeySource;
|
|
60
|
+
env: Record<string, string | undefined>;
|
|
61
|
+
}) => SiteKeySourceMaterial | undefined;
|
|
62
|
+
readonly moveSiteKeyFileAside: (required: {
|
|
63
|
+
filePath: string;
|
|
64
|
+
expectedContent: string;
|
|
65
|
+
}) => string | undefined;
|
|
66
|
+
readonly atomicCreateSiteKeyFile: (required: {
|
|
67
|
+
filePath: string;
|
|
68
|
+
hex: string;
|
|
69
|
+
}) => string;
|
|
70
|
+
readonly stampFingerprint: (required: {
|
|
71
|
+
siteDir: string;
|
|
72
|
+
fingerprint: string;
|
|
73
|
+
}) => void;
|
|
74
|
+
readonly invalidKeyError: (reason: RootKeyRejection) => Error;
|
|
75
|
+
readonly noFileError: () => Error;
|
|
76
|
+
readonly concurrentWriteError: () => Error;
|
|
77
|
+
}
|
|
78
|
+
/** `installed`: the key file now holds `hex` and the stamp names it. `env-key-set`: an env var
|
|
79
|
+
* holding a DIFFERENT key outranks every file (production), so nothing was written. */
|
|
80
|
+
export type InstallSiteKeyResult = {
|
|
81
|
+
readonly outcome: "installed";
|
|
82
|
+
readonly keyFilePath: string;
|
|
83
|
+
readonly fingerprint: string;
|
|
84
|
+
} | {
|
|
85
|
+
readonly outcome: "env-key-set";
|
|
86
|
+
};
|
|
87
|
+
/**
|
|
88
|
+
* Makes `hex` this site's key — the site key tab's recovery writer (design §4.3/§4.6: "Unlock
|
|
89
|
+
* with token", "Start fresh"). The caller has already decided `hex` is right; this only writes it.
|
|
90
|
+
*
|
|
91
|
+
* The target is the first key file in this site's source order (the per-site file locally, the
|
|
92
|
+
* durable-volume file in production). An env var ahead of it that holds a different key would
|
|
93
|
+
* outrank any file, so that is refused (`env-key-set`); one holding `hex` already is fine. A target
|
|
94
|
+
* file holding a different key (or garbage) is moved aside as a backup, never deleted. Then
|
|
95
|
+
* `.site-meta.json`'s `siteKeyFingerprint` is set to `hex`'s (other fields kept; a missing meta
|
|
96
|
+
* file is minted locally, left alone in production).
|
|
97
|
+
*
|
|
98
|
+
* @returns `undefined` when no `siteKeyId` resolves in local mode (an unreadable meta file).
|
|
99
|
+
* @throws {Error} `hex` is not a valid key (nothing written), or the file ends up holding another
|
|
100
|
+
* key (a concurrent writer won the race), or whatever `fs` throws.
|
|
101
|
+
* @complexity O(n) in the (fixed-size) source list, plus a few small file reads/writes.
|
|
102
|
+
*/
|
|
103
|
+
export declare function installSiteKey(input: InstallSiteKeyInput, _optional?: {}): InstallSiteKeyResult | undefined;
|
|
104
|
+
//# sourceMappingURL=files.d.ts.map
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { parseRootKeyHex as parseSiteKeyHex, fingerprintRootKeyHex as fingerprintSiteKeyHex } from "../keyring.env.js";
|
|
2
|
+
import { matchesFingerprint } from "./decide.js";
|
|
3
|
+
import { dirname, join, basename } from "node:path";
|
|
4
|
+
/**
|
|
5
|
+
* Renames a wrong site key file to `<name>.wrong-<timestamp>` beside it (`0600`) so a key is never
|
|
6
|
+
* lost, even one that turned out to be the wrong one. Only moves the file when it still holds
|
|
7
|
+
* `expectedContent`: another instance that already replaced it must not have its fix moved aside.
|
|
8
|
+
* A file already gone (another instance moved it first) is not an error.
|
|
9
|
+
*
|
|
10
|
+
* @returns the backup path, or `undefined` when nothing was moved.
|
|
11
|
+
* @throws whatever `fs` throws other than `ENOENT`.
|
|
12
|
+
* @complexity O(1) — one read, one rename, one chmod.
|
|
13
|
+
*/
|
|
14
|
+
export function moveSiteKeyFileAside({ filePath, expectedContent, fs, nowIso, randomHex, fileMode }, _optional = {}) {
|
|
15
|
+
const { readFileSync, renameSync, chmodSync } = fs;
|
|
16
|
+
let current;
|
|
17
|
+
try {
|
|
18
|
+
current = readFileSync(filePath, "utf8");
|
|
19
|
+
}
|
|
20
|
+
catch (err) {
|
|
21
|
+
if (isErrorCode({ err, code: "ENOENT" }))
|
|
22
|
+
return undefined;
|
|
23
|
+
throw err;
|
|
24
|
+
}
|
|
25
|
+
if (current !== expectedContent)
|
|
26
|
+
return undefined;
|
|
27
|
+
const stamp = nowIso().replace(/[:.]/g, "-");
|
|
28
|
+
const backupPath = `${filePath}.wrong-${stamp}-${randomHex({ bytes: 2 })}`;
|
|
29
|
+
try {
|
|
30
|
+
renameSync(filePath, backupPath);
|
|
31
|
+
}
|
|
32
|
+
catch (err) {
|
|
33
|
+
if (isErrorCode({ err, code: "ENOENT" }))
|
|
34
|
+
return undefined;
|
|
35
|
+
throw err;
|
|
36
|
+
}
|
|
37
|
+
chmodSync(backupPath, fileMode);
|
|
38
|
+
return backupPath;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Writes `hex` to `filePath`, race-safe with no single-instance lock (site-key plan §A.2): write a
|
|
42
|
+
* temp file in the same directory (`0600`, fsynced), then `linkSync` it onto `filePath` — `link(2)`
|
|
43
|
+
* fails atomically with `EEXIST` if anything is already there, so at most one process's bytes ever
|
|
44
|
+
* become the file. The loser's temp file is still removed; its `EEXIST` is swallowed, not
|
|
45
|
+
* propagated. Both the winner and every loser then read `filePath` back and return THAT (never
|
|
46
|
+
* their own `hex` argument), so two instances racing on the same `siteKeyId` always converge on
|
|
47
|
+
* the one file that won, whichever process actually wrote it. Also the project key's publisher
|
|
48
|
+
* (`server/runtime/composition/project-store.ts`), for the same race (web + desktop first start).
|
|
49
|
+
*
|
|
50
|
+
* @param required.filePath - the target `~/.host/site-keys/<id>.hex`. Its containing directory is created
|
|
51
|
+
* (`0700`) if missing.
|
|
52
|
+
* @param required.hex - this call's own candidate key material, used only if no one else wins the race.
|
|
53
|
+
* @returns the final file's content (trimmed) — always read from disk, never `hex` verbatim.
|
|
54
|
+
* @throws whatever `fs` throws other than `EEXIST` from the `linkSync` step.
|
|
55
|
+
* @complexity O(1) — a fixed number of syscalls, independent of `hex`'s length.
|
|
56
|
+
*/
|
|
57
|
+
export function atomicCreateSiteKeyFile({ filePath, hex, fs, pid, randomHex, directoryMode, fileMode }, _optional = {}) {
|
|
58
|
+
const { mkdirSync, openSync, writeSync, fsyncSync, closeSync, chmodSync, linkSync, unlinkSync, readFileSync } = fs;
|
|
59
|
+
const dir = dirname(filePath);
|
|
60
|
+
mkdirSync(dir, { recursive: true, mode: directoryMode });
|
|
61
|
+
const tmpPath = join(dir, `.${basename(filePath)}.tmp-${pid}-${randomHex({ bytes: 4 })}`);
|
|
62
|
+
const fd = openSync(tmpPath, "w", fileMode);
|
|
63
|
+
// The temp file holds key material from the moment it is opened, so every exit (a write, fsync,
|
|
64
|
+
// chmod or link fault included) removes it — not only the link step's.
|
|
65
|
+
try {
|
|
66
|
+
try {
|
|
67
|
+
writeSync(fd, hex);
|
|
68
|
+
fsyncSync(fd);
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
closeSync(fd);
|
|
72
|
+
}
|
|
73
|
+
chmodSync(tmpPath, fileMode);
|
|
74
|
+
try {
|
|
75
|
+
linkSync(tmpPath, filePath);
|
|
76
|
+
}
|
|
77
|
+
catch (err) {
|
|
78
|
+
if (!isErrorCode({ err, code: "EEXIST" }))
|
|
79
|
+
throw err;
|
|
80
|
+
// Lost the race — another process's file is now canonical; fall through to read it back.
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
finally {
|
|
84
|
+
try {
|
|
85
|
+
unlinkSync(tmpPath);
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
// Already gone (e.g. a concurrent cleanup of the same temp name) — nothing left to remove.
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return readFileSync(filePath, "utf8").trim();
|
|
92
|
+
}
|
|
93
|
+
/** Whether a failed fs call failed with exactly `code` (e.g. `EEXIST`: the target path was already
|
|
94
|
+
* taken), as opposed to a genuine I/O or permission fault that must keep propagating. Shared by
|
|
95
|
+
* {@link atomicCreateSiteKeyFile}'s `linkSync` and {@link mintMinimalSiteMetaJson}'s `writeFileSync(…,
|
|
96
|
+
* {flag:"wx"})` — both are "only the FIRST writer wins, everyone else reads the result back"
|
|
97
|
+
* primitives — and by {@link moveSiteKeyFileAside}'s `ENOENT` (another instance moved it first). */
|
|
98
|
+
function isErrorCode({ err, code }, _optional = {}) {
|
|
99
|
+
if (typeof err !== "object" || err === null || !("code" in err))
|
|
100
|
+
return false;
|
|
101
|
+
return err.code === code;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Makes `hex` this site's key — the site key tab's recovery writer (design §4.3/§4.6: "Unlock
|
|
105
|
+
* with token", "Start fresh"). The caller has already decided `hex` is right; this only writes it.
|
|
106
|
+
*
|
|
107
|
+
* The target is the first key file in this site's source order (the per-site file locally, the
|
|
108
|
+
* durable-volume file in production). An env var ahead of it that holds a different key would
|
|
109
|
+
* outrank any file, so that is refused (`env-key-set`); one holding `hex` already is fine. A target
|
|
110
|
+
* file holding a different key (or garbage) is moved aside as a backup, never deleted. Then
|
|
111
|
+
* `.site-meta.json`'s `siteKeyFingerprint` is set to `hex`'s (other fields kept; a missing meta
|
|
112
|
+
* file is minted locally, left alone in production).
|
|
113
|
+
*
|
|
114
|
+
* @returns `undefined` when no `siteKeyId` resolves in local mode (an unreadable meta file).
|
|
115
|
+
* @throws {Error} `hex` is not a valid key (nothing written), or the file ends up holding another
|
|
116
|
+
* key (a concurrent writer won the race), or whatever `fs` throws.
|
|
117
|
+
* @complexity O(n) in the (fixed-size) source list, plus a few small file reads/writes.
|
|
118
|
+
*/
|
|
119
|
+
export function installSiteKey(input, _optional = {}) {
|
|
120
|
+
const parsed = parseSiteKeyHex({ raw: input.hex });
|
|
121
|
+
if (!parsed.ok)
|
|
122
|
+
throw input.invalidKeyError(parsed.reason);
|
|
123
|
+
const resolved = input.resolveInstallSources(input);
|
|
124
|
+
if (resolved === undefined)
|
|
125
|
+
return undefined;
|
|
126
|
+
const target = { input, siteDir: input.siteDir, hex: parsed.hex, fingerprint: fingerprintSiteKeyHex({ hex: parsed.hex }) };
|
|
127
|
+
for (const source of resolved.sources) {
|
|
128
|
+
const installed = installIntoSource({ ...target, source, env: resolved.env });
|
|
129
|
+
if (installed !== undefined)
|
|
130
|
+
return installed;
|
|
131
|
+
}
|
|
132
|
+
throw input.noFileError();
|
|
133
|
+
}
|
|
134
|
+
/** One step of {@link installSiteKey}'s scan: an env source decides only when it holds material,
|
|
135
|
+
* a file source with a path is always the target; anything else is skipped (`undefined`). */
|
|
136
|
+
function installIntoSource(required, _optional = {}) {
|
|
137
|
+
const { source, env, ...target } = required;
|
|
138
|
+
if (source.kind === "env")
|
|
139
|
+
return installAgainstEnvKey({ ...target, material: required.input.readSiteKeySourceMaterial({ source, env }) });
|
|
140
|
+
if (source.path === undefined)
|
|
141
|
+
return undefined;
|
|
142
|
+
return installIntoKeyFile({ ...target, path: source.path, current: required.input.readSiteKeySourceMaterial({ source, env })?.raw });
|
|
143
|
+
}
|
|
144
|
+
/** An env var ahead of every key file: holding a DIFFERENT key it outranks any file, so nothing is
|
|
145
|
+
* written (`env-key-set`); holding `hex` already, only the stamp is set. */
|
|
146
|
+
function installAgainstEnvKey(required, _optional = {}) {
|
|
147
|
+
const { siteDir, fingerprint, material } = required;
|
|
148
|
+
if (material === undefined)
|
|
149
|
+
return undefined;
|
|
150
|
+
if (!matchesFingerprint({ parsed: parseSiteKeyHex({ raw: material.raw }), fingerprint }))
|
|
151
|
+
return { outcome: "env-key-set" };
|
|
152
|
+
required.input.stampFingerprint({ siteDir, fingerprint });
|
|
153
|
+
return { outcome: "installed", keyFilePath: `env:${material.envVarName}`, fingerprint };
|
|
154
|
+
}
|
|
155
|
+
/** Writes `hex` into the target key file, backing up a different (or garbage) one first. */
|
|
156
|
+
function installIntoKeyFile(required, _optional = {}) {
|
|
157
|
+
const { siteDir, hex, fingerprint, path, current } = required;
|
|
158
|
+
if (current !== undefined && !matchesFingerprint({ parsed: parseSiteKeyHex({ raw: current }), fingerprint }))
|
|
159
|
+
required.input.moveSiteKeyFileAside({ filePath: path, expectedContent: current });
|
|
160
|
+
const written = required.input.atomicCreateSiteKeyFile({ filePath: path, hex });
|
|
161
|
+
if (fingerprintSiteKeyHex({ hex: written }) !== fingerprint)
|
|
162
|
+
throw required.input.concurrentWriteError();
|
|
163
|
+
required.input.stampFingerprint({ siteDir, fingerprint });
|
|
164
|
+
return { outcome: "installed", keyFilePath: path, fingerprint };
|
|
165
|
+
}
|
|
166
|
+
//# sourceMappingURL=files.js.map
|