@xlinklight/publishing 3.3.0 → 3.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -3
- package/dist/src/acceptance-delivery-binding.d.ts +20 -0
- package/dist/src/acceptance-delivery-binding.js +59 -0
- package/dist/src/acceptance.d.ts +49 -0
- package/dist/src/acceptance.js +79 -0
- package/dist/src/client.d.ts +71 -0
- package/dist/src/client.js +146 -0
- package/dist/src/index.d.ts +6 -0
- package/dist/src/index.js +3 -0
- package/dist/src/node/acceptance-delivery.d.ts +34 -0
- package/dist/src/node/acceptance-delivery.js +88 -0
- package/dist/src/node/activation.d.ts +5 -0
- package/dist/src/node/activation.js +3 -0
- package/dist/src/node/authorization.d.ts +31 -0
- package/dist/src/node/authorization.js +76 -0
- package/dist/src/node/cli.d.ts +2 -0
- package/dist/src/node/cli.js +22 -0
- package/dist/src/node/index.d.ts +20 -0
- package/dist/src/node/index.js +11 -0
- package/dist/src/node/journal-directory.d.ts +2 -0
- package/dist/src/node/journal-directory.js +121 -0
- package/dist/src/node/journal.d.ts +49 -0
- package/dist/src/node/journal.js +280 -0
- package/dist/src/node/local-json-file.d.ts +3 -0
- package/dist/src/node/local-json-file.js +49 -0
- package/dist/src/node/publishing-command.d.ts +46 -0
- package/dist/src/node/publishing-command.js +268 -0
- package/dist/src/node/session.d.ts +95 -0
- package/dist/src/node/session.js +223 -0
- package/dist/src/node/solution-package.d.ts +55 -0
- package/dist/src/node/solution-package.js +217 -0
- package/dist/src/node/source-error.d.ts +10 -0
- package/dist/src/node/source-error.js +15 -0
- package/dist/src/node/source-producer.d.ts +5 -0
- package/dist/src/node/source-producer.js +145 -0
- package/dist/src/node/terminal-network.d.ts +23 -0
- package/dist/src/node/terminal-network.js +122 -0
- package/dist/src/node/workflow.d.ts +74 -0
- package/dist/src/node/workflow.js +467 -0
- package/dist/src/package.d.ts +38 -0
- package/dist/src/package.js +74 -0
- package/dist/src/protocol.d.ts +83 -0
- package/dist/src/protocol.js +105 -0
- package/dist/src/shared/activation-types.d.ts +37 -0
- package/dist/src/shared/activation-types.js +1 -0
- package/dist/src/shared/activation.d.ts +17 -0
- package/dist/src/shared/activation.js +111 -0
- package/dist/src/shared/records.d.ts +10 -0
- package/dist/src/shared/records.js +26 -0
- package/dist/src/shared/release-version.d.ts +4 -0
- package/dist/src/shared/release-version.js +15 -0
- package/dist/src/worker/activation.d.ts +12 -0
- package/dist/src/worker/activation.js +11 -0
- package/dist/src/worker/durable-retention.d.ts +9 -0
- package/dist/src/worker/durable-retention.js +96 -0
- package/dist/src/worker/index.d.ts +12 -0
- package/dist/src/worker/index.js +7 -0
- package/dist/src/worker/journal.d.ts +129 -0
- package/dist/src/worker/journal.js +328 -0
- package/dist/src/worker/package.d.ts +60 -0
- package/dist/src/worker/package.js +116 -0
- package/dist/src/worker/release-retention.d.ts +34 -0
- package/dist/src/worker/release-retention.js +27 -0
- package/dist/src/worker/release.d.ts +22 -0
- package/dist/src/worker/release.js +59 -0
- package/dist/src/worker/runtime.d.ts +47 -0
- package/dist/src/worker/runtime.js +98 -0
- package/dist/src/worker/service.d.ts +128 -0
- package/dist/src/worker/service.js +520 -0
- package/package.json +23 -14
- package/src/acceptance-delivery-binding.mjs +0 -49
- package/src/acceptance.d.mts +0 -24
- package/src/acceptance.mjs +0 -67
- package/src/client.d.mts +0 -16
- package/src/client.mjs +0 -74
- package/src/index.d.mts +0 -6
- package/src/index.mjs +0 -3
- package/src/node/acceptance-delivery.d.mts +0 -11
- package/src/node/acceptance-delivery.mjs +0 -70
- package/src/node/activation.d.mts +0 -8
- package/src/node/activation.mjs +0 -3
- package/src/node/authorization.d.mts +0 -8
- package/src/node/authorization.mjs +0 -49
- package/src/node/cli.mjs +0 -12
- package/src/node/index.d.mts +0 -17
- package/src/node/index.mjs +0 -9
- package/src/node/journal.d.mts +0 -13
- package/src/node/journal.mjs +0 -135
- package/src/node/publishing-command.d.mts +0 -20
- package/src/node/publishing-command.mjs +0 -104
- package/src/node/session.d.mts +0 -25
- package/src/node/session.mjs +0 -134
- package/src/node/solution-package.d.mts +0 -15
- package/src/node/solution-package.mjs +0 -113
- package/src/node/source-error.d.mts +0 -5
- package/src/node/source-error.mjs +0 -9
- package/src/node/source-producer.mjs +0 -103
- package/src/node/workflow.d.mts +0 -37
- package/src/node/workflow.mjs +0 -320
- package/src/package.d.mts +0 -11
- package/src/package.mjs +0 -36
- package/src/protocol.d.mts +0 -27
- package/src/protocol.mjs +0 -50
- package/src/shared/activation.d.mts +0 -5
- package/src/shared/activation.mjs +0 -64
- package/src/worker/activation.d.mts +0 -7
- package/src/worker/activation.mjs +0 -4
- package/src/worker/index.d.mts +0 -6
- package/src/worker/index.mjs +0 -6
- package/src/worker/journal.d.mts +0 -21
- package/src/worker/journal.mjs +0 -151
- package/src/worker/package.d.mts +0 -16
- package/src/worker/package.mjs +0 -32
- package/src/worker/release.d.mts +0 -7
- package/src/worker/release.mjs +0 -21
- package/src/worker/runtime.d.mts +0 -4
- package/src/worker/runtime.mjs +0 -23
- package/src/worker/service.d.mts +0 -41
- package/src/worker/service.mjs +0 -251
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { PublishingJournal } from './journal.js';
|
|
2
|
+
import type { AcceptanceDeliveryCredential } from './acceptance-delivery.js';
|
|
3
|
+
import type { PublishingConfiguration } from '../protocol.js';
|
|
4
|
+
import type { PublishingClientLimits } from '../client.js';
|
|
5
|
+
export interface PublishingAuthorization {
|
|
6
|
+
configuration: PublishingConfiguration;
|
|
7
|
+
credential: string;
|
|
8
|
+
acceptanceDelivery?: AcceptanceDeliveryCredential;
|
|
9
|
+
}
|
|
10
|
+
/** The caller supplies private persistent storage, including access controls and
|
|
11
|
+
* backup policy. No provider credential or process/global setting is stored. */
|
|
12
|
+
export declare function loadPublishingAuthorization({ journal, allowLoopback, signal }: {
|
|
13
|
+
journal: Pick<PublishingJournal, 'load' | 'compareAndSet'>;
|
|
14
|
+
allowLoopback?: boolean;
|
|
15
|
+
signal?: AbortSignal;
|
|
16
|
+
}): Promise<PublishingAuthorization | undefined>;
|
|
17
|
+
/** Validate installed trust and current project access before atomic install.
|
|
18
|
+
* A changed service/publisher trust never adopts an existing recovery journal. */
|
|
19
|
+
export declare function installPublishingAuthorization({ journal, configuration: input, credential, acceptanceDelivery, replaceCredential, allowLoopback, request, clientLimits, signal }: PublishingAuthorization & {
|
|
20
|
+
journal: Pick<PublishingJournal, 'load' | 'compareAndSet'>;
|
|
21
|
+
replaceCredential?: boolean;
|
|
22
|
+
allowLoopback?: boolean;
|
|
23
|
+
request?: typeof fetch;
|
|
24
|
+
clientLimits?: PublishingClientLimits;
|
|
25
|
+
signal?: AbortSignal;
|
|
26
|
+
}): Promise<{
|
|
27
|
+
status: 'CONFIGURED' | 'VERIFIED' | 'REPLACED';
|
|
28
|
+
projectId: string;
|
|
29
|
+
credentialSha256: string;
|
|
30
|
+
policyRevision: number;
|
|
31
|
+
}>;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { createHash, createPublicKey } from 'node:crypto';
|
|
2
|
+
import { parseAcceptanceDeliveryCredential } from './acceptance-delivery.js';
|
|
3
|
+
import { createPublishingClient } from '../client.js';
|
|
4
|
+
import { parsePublishingConfiguration, protocolRecord, publishingError } from '../protocol.js';
|
|
5
|
+
const key = 'client-authorization', hash = (value) => createHash('sha256').update(value).digest('hex'), fail = (code) => publishingError('CREDENTIAL_' + code);
|
|
6
|
+
const credentialValid = (value) => typeof value === 'string' && /^[A-Za-z0-9_-]{32,4096}$/.test(value);
|
|
7
|
+
function saved(record, allowLoopback) {
|
|
8
|
+
if (!record)
|
|
9
|
+
return undefined;
|
|
10
|
+
const value = record.payload;
|
|
11
|
+
if (!protocolRecord(value, ['schemaVersion', 'configuration', 'configurationSha256', 'credential', 'credentialSha256'], ['acceptanceDelivery']) || value.schemaVersion !== 1 || !credentialValid(value.credential))
|
|
12
|
+
throw fail('INVALID');
|
|
13
|
+
let configuration;
|
|
14
|
+
try {
|
|
15
|
+
configuration = parsePublishingConfiguration(value.configuration, { allowLoopback });
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
throw fail('INVALID');
|
|
19
|
+
}
|
|
20
|
+
if (hash(JSON.stringify(configuration)) !== value.configurationSha256 || hash(value.credential) !== value.credentialSha256)
|
|
21
|
+
throw fail('INVALID');
|
|
22
|
+
return { configuration, credential: value.credential, ...(value.acceptanceDelivery ? { acceptanceDelivery: parseAcceptanceDeliveryCredential(value.acceptanceDelivery) } : {}) };
|
|
23
|
+
}
|
|
24
|
+
function store(journal) { if (!journal || typeof journal.load !== 'function' || typeof journal.compareAndSet !== 'function')
|
|
25
|
+
throw fail('STORE_INVALID'); return journal; }
|
|
26
|
+
/** The caller supplies private persistent storage, including access controls and
|
|
27
|
+
* backup policy. No provider credential or process/global setting is stored. */
|
|
28
|
+
export async function loadPublishingAuthorization({ journal, allowLoopback = false, signal }) {
|
|
29
|
+
signal?.throwIfAborted();
|
|
30
|
+
return saved(await store(journal).load(key, { signal }), allowLoopback);
|
|
31
|
+
}
|
|
32
|
+
/** Validate installed trust and current project access before atomic install.
|
|
33
|
+
* A changed service/publisher trust never adopts an existing recovery journal. */
|
|
34
|
+
export async function installPublishingAuthorization({ journal, configuration: input, credential, acceptanceDelivery, replaceCredential = false, allowLoopback = false, request, clientLimits, signal }) {
|
|
35
|
+
store(journal);
|
|
36
|
+
signal?.throwIfAborted();
|
|
37
|
+
const configuration = parsePublishingConfiguration(input, { allowLoopback });
|
|
38
|
+
if (!credentialValid(credential) || typeof replaceCredential !== 'boolean')
|
|
39
|
+
throw fail('INVALID');
|
|
40
|
+
const previous = await journal.load(key, { signal }), current = saved(previous, allowLoopback), configurationSha256 = hash(JSON.stringify(configuration)), credentialSha256 = hash(credential);
|
|
41
|
+
if (current && JSON.stringify(current.configuration) !== JSON.stringify(configuration))
|
|
42
|
+
throw fail('TRUST_CHANGED');
|
|
43
|
+
if (current && current.credential !== credential && !replaceCredential)
|
|
44
|
+
throw fail('REPLACEMENT_REQUIRED');
|
|
45
|
+
const delivery = acceptanceDelivery === undefined ? current?.acceptanceDelivery : parseAcceptanceDeliveryCredential(acceptanceDelivery);
|
|
46
|
+
if (delivery) {
|
|
47
|
+
const publicBytes = (key) => createPublicKey(key).export({ type: 'spki', format: 'der' });
|
|
48
|
+
if (configuration.publisher.keys.some(key => publicBytes(key.publicKey).equals(publicBytes(delivery.privateKey))))
|
|
49
|
+
throw fail('TRUST_CHANGED');
|
|
50
|
+
if (current?.acceptanceDelivery && (delivery.origin !== current.acceptanceDelivery.origin || delivery.keyId !== current.acceptanceDelivery.keyId ||
|
|
51
|
+
!publicBytes(delivery.privateKey).equals(publicBytes(current.acceptanceDelivery.privateKey))))
|
|
52
|
+
throw fail('TRUST_CHANGED');
|
|
53
|
+
if (current?.acceptanceDelivery && JSON.stringify(current.acceptanceDelivery) !== JSON.stringify(delivery) && !replaceCredential)
|
|
54
|
+
throw fail('REPLACEMENT_REQUIRED');
|
|
55
|
+
}
|
|
56
|
+
const client = createPublishingClient({ configuration, credential, allowLoopback, ...(request ? { request } : {}), ...(clientLimits ? { limits: clientLimits } : {}) }), project = await client.getProject({ signal });
|
|
57
|
+
if (current?.credential === credential && JSON.stringify(current.acceptanceDelivery) === JSON.stringify(delivery)) {
|
|
58
|
+
const latest = await journal.load(key, { signal });
|
|
59
|
+
if (!previous || latest?.revision !== previous.revision)
|
|
60
|
+
throw fail('CONFLICT');
|
|
61
|
+
saved(latest, allowLoopback);
|
|
62
|
+
return { status: 'VERIFIED', projectId: configuration.projectId, credentialSha256, policyRevision: project.policyRevision };
|
|
63
|
+
}
|
|
64
|
+
let result;
|
|
65
|
+
try {
|
|
66
|
+
result = await journal.compareAndSet({ key, expectedRevision: previous?.revision ?? 0, payload: { schemaVersion: 1, configuration: { ...configuration }, configurationSha256, credential, credentialSha256, ...(delivery ? { acceptanceDelivery: { ...delivery } } : {}) } }, { signal });
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
throw fail('PERSISTENCE_UNKNOWN');
|
|
70
|
+
}
|
|
71
|
+
if (result === 'conflict')
|
|
72
|
+
throw fail('CONFLICT');
|
|
73
|
+
if (result !== 'stored')
|
|
74
|
+
throw fail('PERSISTENCE_UNKNOWN');
|
|
75
|
+
return { status: previous ? 'REPLACED' : 'CONFIGURED', projectId: configuration.projectId, credentialSha256, policyRevision: project.policyRevision };
|
|
76
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { existsSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { runPublishingTerminalCommand } from './publishing-command.js';
|
|
5
|
+
async function main() {
|
|
6
|
+
const proxy = process.env.LINK_LIGHT_PUBLISHING_PROXY;
|
|
7
|
+
delete process.env.LINK_LIGHT_PUBLISHING_PROXY;
|
|
8
|
+
const controller = new AbortController(), stop = () => controller.abort();
|
|
9
|
+
process.once('SIGINT', stop);
|
|
10
|
+
process.once('SIGTERM', stop);
|
|
11
|
+
try {
|
|
12
|
+
const result = await runPublishingTerminalCommand(process.argv.slice(2), controller.signal, proxy);
|
|
13
|
+
process.stdout.write(JSON.stringify(result.output) + '\n');
|
|
14
|
+
process.exitCode = result.exitCode;
|
|
15
|
+
}
|
|
16
|
+
finally {
|
|
17
|
+
process.off('SIGINT', stop);
|
|
18
|
+
process.off('SIGTERM', stop);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
if (process.argv[1] && existsSync(process.argv[1]) && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)))
|
|
22
|
+
void main();
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export type { SolutionPackageLimits, SolutionPackageFilePlan, PreparedSolutionPackage } from './solution-package.js';
|
|
2
|
+
export type { PublishingMetadataTransport } from '../protocol.js';
|
|
3
|
+
export type { PublishingJournal, PublishingJournalRecord, PublishingJournalLimits } from './journal.js';
|
|
4
|
+
export type { PublishingSession, PublishingSessionResult } from './session.js';
|
|
5
|
+
export type { PublishingAuthorization } from './authorization.js';
|
|
6
|
+
export type { PublishingActivation } from './activation.js';
|
|
7
|
+
export type { PublishingSourceProducer, PublishingWorkflowOptions, PublishingSourceOptions, PublishingPublishOptions, PublishingWorkflowResult, PublishingWorkflow } from './workflow.js';
|
|
8
|
+
export type { PublishingCommandOptions, PublishingCommandResult } from './publishing-command.js';
|
|
9
|
+
export type { AcceptanceArchive, AcceptanceArchiveIdentity, AcceptanceDeliveryBinding, AcceptanceDeliveryCredential } from './acceptance-delivery.js';
|
|
10
|
+
export { prepareSolutionPackage, prepareSolutionPackageBytes, verifySolutionPackage, verifySolutionPackageBytes } from './solution-package.js';
|
|
11
|
+
export { openPublishingJournal } from './journal.js';
|
|
12
|
+
export { createPublishingSession } from './session.js';
|
|
13
|
+
export { installPublishingAuthorization, loadPublishingAuthorization } from './authorization.js';
|
|
14
|
+
export { createPublishingActivation, verifyPublishingActivation } from './activation.js';
|
|
15
|
+
export { PublishingSourceError } from './source-error.js';
|
|
16
|
+
export { createPublishingWorkflow } from './workflow.js';
|
|
17
|
+
export { publishingVersionRequestId } from '../shared/release-version.js';
|
|
18
|
+
export { discoverWindowsProxyRoutes, openPublishingTerminalNetwork } from './terminal-network.js';
|
|
19
|
+
export { deliverAcceptanceArchive, signAcceptanceDelivery, maximumAcceptanceArchiveBytes, readDeliveryBody, verifyAcceptanceDelivery } from './acceptance-delivery.js';
|
|
20
|
+
export { runPublishingCommand } from './publishing-command.js';
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { prepareSolutionPackage, prepareSolutionPackageBytes, verifySolutionPackage, verifySolutionPackageBytes } from './solution-package.js';
|
|
2
|
+
export { openPublishingJournal } from './journal.js';
|
|
3
|
+
export { createPublishingSession } from './session.js';
|
|
4
|
+
export { installPublishingAuthorization, loadPublishingAuthorization } from './authorization.js';
|
|
5
|
+
export { createPublishingActivation, verifyPublishingActivation } from './activation.js';
|
|
6
|
+
export { PublishingSourceError } from './source-error.js';
|
|
7
|
+
export { createPublishingWorkflow } from './workflow.js';
|
|
8
|
+
export { publishingVersionRequestId } from '../shared/release-version.js';
|
|
9
|
+
export { discoverWindowsProxyRoutes, openPublishingTerminalNetwork } from './terminal-network.js';
|
|
10
|
+
export { deliverAcceptanceArchive, signAcceptanceDelivery, maximumAcceptanceArchiveBytes, readDeliveryBody, verifyAcceptanceDelivery } from './acceptance-delivery.js';
|
|
11
|
+
export { runPublishingCommand } from './publishing-command.js';
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import type { DurableArtifactFilesystem } from '@openge/forge-generated-artifacts/node';
|
|
2
|
+
export declare function ensurePublishingJournalDirectory(root: string, relative: string, filesystem: DurableArtifactFilesystem, credential: boolean, signal?: AbortSignal): Promise<string>;
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { promisify } from 'node:util';
|
|
5
|
+
import { publishingError } from '../protocol.js';
|
|
6
|
+
const execute = promisify(execFile);
|
|
7
|
+
const privateRequired = () => publishingError('JOURNAL_PRIVATE_REQUIRED');
|
|
8
|
+
const boundary = () => publishingError('JOURNAL_BOUNDARY');
|
|
9
|
+
const journalFiles = ['owner.json', 'journal.sqlite', 'journal.sqlite-journal'];
|
|
10
|
+
const missing = (err) => err instanceof Error && 'code' in err && err.code === 'ENOENT';
|
|
11
|
+
// CreateDirectory's security descriptor applies when Windows creates the object.
|
|
12
|
+
// An existing directory keeps its ACL and must already grant private access.
|
|
13
|
+
const windowsSecurity = `$ErrorActionPreference='Stop'
|
|
14
|
+
try {
|
|
15
|
+
$target=$env:PUBLISHING_JOURNAL_DIRECTORY
|
|
16
|
+
$sidType=[Security.Principal.SecurityIdentifier]
|
|
17
|
+
$user=[Security.Principal.WindowsIdentity]::GetCurrent().User
|
|
18
|
+
$allowed=@($user.Value,'S-1-5-18','S-1-5-32-544')
|
|
19
|
+
$dir=[IO.DirectoryInfo]::new($target)
|
|
20
|
+
if(!$dir.Exists){
|
|
21
|
+
if($env:PUBLISHING_JOURNAL_CREATE -ne '1' -or !$dir.Parent.Exists){exit 1}
|
|
22
|
+
$acl=[Security.AccessControl.DirectorySecurity]::new()
|
|
23
|
+
$acl.SetAccessRuleProtection($true,$false)
|
|
24
|
+
$acl.SetOwner($user)
|
|
25
|
+
foreach($id in $allowed){
|
|
26
|
+
$account=[Security.Principal.SecurityIdentifier]::new($id)
|
|
27
|
+
$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($account,'FullControl','ContainerInherit,ObjectInherit','None','Allow'))
|
|
28
|
+
}
|
|
29
|
+
$dir=[IO.Directory]::CreateDirectory($target,$acl)
|
|
30
|
+
}
|
|
31
|
+
function Assert-Private($item,$directory){
|
|
32
|
+
if(($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0){exit 1}
|
|
33
|
+
$security=$item.GetAccessControl()
|
|
34
|
+
$raw=[Security.AccessControl.RawSecurityDescriptor]::new($security.GetSecurityDescriptorBinaryForm(),0)
|
|
35
|
+
if($null -eq $raw.DiscretionaryAcl -or $allowed -notcontains $raw.Owner.Value){exit 1}
|
|
36
|
+
$inherits=$false
|
|
37
|
+
foreach($ace in $raw.DiscretionaryAcl){
|
|
38
|
+
if($ace.AceType -eq 'AccessDenied'){continue}
|
|
39
|
+
if($ace.AceType -ne 'AccessAllowed' -or $allowed -notcontains $ace.SecurityIdentifier.Value){exit 1}
|
|
40
|
+
if(([int]$ace.AceFlags -band [int][Security.AccessControl.AceFlags]::ObjectInherit) -ne 0){$inherits=$true}
|
|
41
|
+
}
|
|
42
|
+
if($directory -and !$inherits){exit 1}
|
|
43
|
+
}
|
|
44
|
+
Assert-Private $dir $true
|
|
45
|
+
foreach($leaf in @('owner.json','journal.sqlite','journal.sqlite-journal')){
|
|
46
|
+
$file=[IO.FileInfo]::new([IO.Path]::Combine($target,$leaf))
|
|
47
|
+
if($file.Exists){Assert-Private $file $false}
|
|
48
|
+
}
|
|
49
|
+
}catch{exit 1}`;
|
|
50
|
+
async function windowsDirectory(directory, create, signal) {
|
|
51
|
+
const system = process.env.SystemRoot;
|
|
52
|
+
if (!system || !path.isAbsolute(system))
|
|
53
|
+
throw privateRequired();
|
|
54
|
+
try {
|
|
55
|
+
await execute(path.join(system, 'System32/WindowsPowerShell/v1.0/powershell.exe'), ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(windowsSecurity, 'utf16le').toString('base64')], { env: { SystemRoot: system, WINDIR: system, PUBLISHING_JOURNAL_DIRECTORY: directory, PUBLISHING_JOURNAL_CREATE: create ? '1' : '0' },
|
|
56
|
+
windowsHide: true, timeout: 10000, maxBuffer: 4096, signal });
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
throw privateRequired();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
async function directoryIdentity(directory) {
|
|
63
|
+
const info = await fs.lstat(directory, { bigint: true });
|
|
64
|
+
if (!info.isDirectory() || info.isSymbolicLink() || await fs.realpath(directory) !== directory)
|
|
65
|
+
throw boundary();
|
|
66
|
+
return info;
|
|
67
|
+
}
|
|
68
|
+
async function syncDirectory(filesystem, root, relative) {
|
|
69
|
+
try {
|
|
70
|
+
await filesystem.ensureDirectory(root, relative);
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
throw publishingError('JOURNAL_PERSISTENCE_UNKNOWN');
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
async function privatePosixFiles(directory) {
|
|
77
|
+
const uid = process.geteuid?.();
|
|
78
|
+
if (uid === undefined)
|
|
79
|
+
throw privateRequired();
|
|
80
|
+
const parent = await directoryIdentity(directory);
|
|
81
|
+
if (parent.uid !== BigInt(uid) || (parent.mode & 63n) !== 0n)
|
|
82
|
+
throw privateRequired();
|
|
83
|
+
for (const name of journalFiles) {
|
|
84
|
+
const file = path.join(directory, name), info = await fs.lstat(file).catch((err) => { if (missing(err))
|
|
85
|
+
return; throw err; });
|
|
86
|
+
if (info && (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || info.uid !== uid || (info.mode & 0o077) !== 0))
|
|
87
|
+
throw privateRequired();
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
export async function ensurePublishingJournalDirectory(root, relative, filesystem, credential, signal) {
|
|
91
|
+
const directory = path.join(root, ...relative.split('/')), parent = path.dirname(directory);
|
|
92
|
+
if (process.platform !== 'win32') {
|
|
93
|
+
await syncDirectory(filesystem, root, relative);
|
|
94
|
+
if (credential)
|
|
95
|
+
await privatePosixFiles(directory);
|
|
96
|
+
return directory;
|
|
97
|
+
}
|
|
98
|
+
const before = await directoryIdentity(directory).catch((err) => { if (missing(err))
|
|
99
|
+
return; throw err; });
|
|
100
|
+
if (before && !credential) {
|
|
101
|
+
await syncDirectory(filesystem, root, relative);
|
|
102
|
+
const current = await directoryIdentity(directory);
|
|
103
|
+
if (current.dev !== before.dev || current.ino !== before.ino)
|
|
104
|
+
throw boundary();
|
|
105
|
+
return directory;
|
|
106
|
+
}
|
|
107
|
+
// Foundation verifies the ancestry and synchronizes new parents. Only the journal leaf receives the private descriptor.
|
|
108
|
+
const relativeParent = path.posix.dirname(relative);
|
|
109
|
+
await syncDirectory(filesystem, root, relativeParent === '.' ? '' : relativeParent);
|
|
110
|
+
const beforeParent = await directoryIdentity(parent);
|
|
111
|
+
await windowsDirectory(directory, !before, signal);
|
|
112
|
+
const expected = await directoryIdentity(directory);
|
|
113
|
+
if (before && (before.dev !== expected.dev || before.ino !== expected.ino))
|
|
114
|
+
throw boundary();
|
|
115
|
+
await syncDirectory(filesystem, root, relative);
|
|
116
|
+
const identity = await directoryIdentity(directory), afterParent = await directoryIdentity(parent);
|
|
117
|
+
if (beforeParent.dev !== afterParent.dev || beforeParent.ino !== afterParent.ino ||
|
|
118
|
+
expected.dev !== identity.dev || expected.ino !== identity.ino)
|
|
119
|
+
throw boundary();
|
|
120
|
+
return directory;
|
|
121
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { JsonValue } from '@xlinklight/contracts';
|
|
2
|
+
import type { ArtifactOperationJournal } from '@openge/forge-artifact-publish';
|
|
3
|
+
import type { DurableArtifactFilesystem } from '@openge/forge-generated-artifacts/node';
|
|
4
|
+
export interface PublishingJournalLimits {
|
|
5
|
+
maximumBytes: number;
|
|
6
|
+
maximumRecords: number;
|
|
7
|
+
maximumRecordBytes: number;
|
|
8
|
+
maximumBlobs: number;
|
|
9
|
+
maximumBlobBytes: number;
|
|
10
|
+
minimumFreeBytes: number;
|
|
11
|
+
}
|
|
12
|
+
export interface PublishingJournalRecord {
|
|
13
|
+
revision: number;
|
|
14
|
+
payload: JsonValue;
|
|
15
|
+
}
|
|
16
|
+
export interface PublishingJournal {
|
|
17
|
+
load(key: string, options?: {
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
}): Promise<PublishingJournalRecord | undefined>;
|
|
20
|
+
readBlob(input: {
|
|
21
|
+
sha256: string;
|
|
22
|
+
byteLength: number;
|
|
23
|
+
}, options?: {
|
|
24
|
+
signal?: AbortSignal;
|
|
25
|
+
}): Promise<Uint8Array | undefined>;
|
|
26
|
+
compareAndSet(input: {
|
|
27
|
+
key: string;
|
|
28
|
+
expectedRevision: number;
|
|
29
|
+
payload: JsonValue;
|
|
30
|
+
blobs?: readonly {
|
|
31
|
+
sha256: string;
|
|
32
|
+
bytes: Uint8Array;
|
|
33
|
+
}[];
|
|
34
|
+
}, options?: {
|
|
35
|
+
signal?: AbortSignal;
|
|
36
|
+
}): Promise<'stored' | 'conflict'>;
|
|
37
|
+
operationJournal(): ArtifactOperationJournal;
|
|
38
|
+
close(): void;
|
|
39
|
+
}
|
|
40
|
+
type JournalInput = {
|
|
41
|
+
root: string;
|
|
42
|
+
directory: string;
|
|
43
|
+
filesystem: DurableArtifactFilesystem;
|
|
44
|
+
limits: PublishingJournalLimits;
|
|
45
|
+
signal?: AbortSignal;
|
|
46
|
+
};
|
|
47
|
+
export declare function openPublishingJournal(input: JournalInput): Promise<PublishingJournal>;
|
|
48
|
+
export declare function openPublishingCredentialJournal(input: JournalInput): Promise<PublishingJournal>;
|
|
49
|
+
export {};
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
4
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
5
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
6
|
+
import { validatePortableRelativePath } from '@openge/forge-path-safety';
|
|
7
|
+
import { GeneratedArtifactError, generatedArtifactErrorCodes } from '@openge/forge-generated-artifacts';
|
|
8
|
+
import { publishingError, protocolRecord, publishingRequestId, publishingDigest } from '../protocol.js';
|
|
9
|
+
import { jsonSnapshot, operationRecord } from '../shared/records.js';
|
|
10
|
+
import { ensurePublishingJournalDirectory } from './journal-directory.js';
|
|
11
|
+
const fail = (code) => publishingError('JOURNAL_' + code);
|
|
12
|
+
const keyValid = (value) => typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,191}$/.test(value);
|
|
13
|
+
const recordBytes = (key, revision, payload) => Buffer.byteLength('{"key":' + JSON.stringify(key) + ',"revision":' + revision + ',"payload":' + payload + '}');
|
|
14
|
+
const fileMissing = (error) => error instanceof Error && 'code' in error && error.code === 'ENOENT';
|
|
15
|
+
function storageFailure(error) {
|
|
16
|
+
if (error && typeof error === 'object' && 'code' in error && typeof error.code === 'string' && error.code.startsWith('PUBLISHING_'))
|
|
17
|
+
throw error;
|
|
18
|
+
const code = error && typeof error === 'object' && 'errcode' in error ? error.errcode : undefined;
|
|
19
|
+
throw fail(code === 5 || code === 6 ? 'BUSY' : 'STORAGE_UNKNOWN');
|
|
20
|
+
}
|
|
21
|
+
function checkedLimits(value) {
|
|
22
|
+
if (!protocolRecord(value, ['maximumBytes', 'maximumRecords', 'maximumRecordBytes', 'maximumBlobs', 'maximumBlobBytes', 'minimumFreeBytes']) || !Object.values(value).every(Number.isSafeInteger) || value.maximumBytes < 65536 || value.maximumBytes > 1073741824 || value.maximumRecords < 1 || value.maximumRecords > 4096 || value.maximumRecordBytes < 1 || value.maximumRecordBytes > 1048576 || value.maximumBlobs < 1 || value.maximumBlobs > 32768 || value.maximumBlobBytes < 1 || value.maximumBlobBytes > 134217728 || value.minimumFreeBytes < 0)
|
|
23
|
+
throw fail('LIMIT_INVALID');
|
|
24
|
+
return { ...value };
|
|
25
|
+
}
|
|
26
|
+
const occupied = (error) => error instanceof GeneratedArtifactError && error.code === generatedArtifactErrorCodes.destinationOccupied && error.details.cleanupFailed !== true;
|
|
27
|
+
async function capacity(root, limits) {
|
|
28
|
+
const info = await fs.statfs(root, { bigint: true });
|
|
29
|
+
if (info.bavail * info.bsize < BigInt(limits.minimumFreeBytes) + BigInt(limits.maximumBytes) * 2n + 65536n)
|
|
30
|
+
throw fail('CAPACITY_REQUIRED');
|
|
31
|
+
}
|
|
32
|
+
async function markerBytes(file) {
|
|
33
|
+
const before = await fs.lstat(file, { bigint: true });
|
|
34
|
+
if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1n || before.size > 4096n || await fs.realpath(file) !== file)
|
|
35
|
+
throw fail('OWNERSHIP_INVALID');
|
|
36
|
+
const body = await fs.readFile(file), after = await fs.lstat(file, { bigint: true });
|
|
37
|
+
if (body.byteLength > 4096 || ['dev', 'ino', 'size', 'mtimeNs', 'ctimeNs'].some(key => before[key] !== after[key]))
|
|
38
|
+
throw fail('OWNERSHIP_INVALID');
|
|
39
|
+
try {
|
|
40
|
+
return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(body));
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
throw fail('OWNERSHIP_INVALID');
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
export function openPublishingJournal(input) { return openJournal(input, false); }
|
|
47
|
+
export function openPublishingCredentialJournal(input) { return openJournal(input, true); }
|
|
48
|
+
/** SQLite owns CAS; Foundation owns durable publication of the directory/owner bytes. */
|
|
49
|
+
async function openJournal({ root, directory, filesystem, limits, signal }, credential) {
|
|
50
|
+
signal?.throwIfAborted();
|
|
51
|
+
limits = checkedLimits(limits);
|
|
52
|
+
if (typeof root !== 'string' || !path.isAbsolute(root) || !filesystem || typeof filesystem.ensureDirectory !== 'function' || typeof filesystem.publishBytes !== 'function')
|
|
53
|
+
throw fail('INPUT_INVALID');
|
|
54
|
+
root = path.resolve(root);
|
|
55
|
+
const rootInfo = await fs.lstat(root, { bigint: true });
|
|
56
|
+
if (!rootInfo.isDirectory() || rootInfo.isSymbolicLink() || await fs.realpath(root) !== root)
|
|
57
|
+
throw fail('BOUNDARY');
|
|
58
|
+
try {
|
|
59
|
+
directory = validatePortableRelativePath(directory);
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
throw fail('BOUNDARY');
|
|
63
|
+
}
|
|
64
|
+
await capacity(root, limits);
|
|
65
|
+
signal?.throwIfAborted();
|
|
66
|
+
const absolute = await ensurePublishingJournalDirectory(root, directory, filesystem, credential, signal);
|
|
67
|
+
const markerFile = path.join(absolute, 'owner.json'), databaseFile = path.join(absolute, 'journal.sqlite');
|
|
68
|
+
const context = { schemaVersion: 1, root: { dev: String(rootInfo.dev), ino: String(rootInfo.ino) }, directory, limits };
|
|
69
|
+
let marker;
|
|
70
|
+
try {
|
|
71
|
+
marker = await markerBytes(markerFile);
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
if (!fileMissing(error))
|
|
75
|
+
throw error;
|
|
76
|
+
if ((await fs.readdir(absolute)).length)
|
|
77
|
+
throw fail('OCCUPIED');
|
|
78
|
+
const value = { ...context, ownerId: randomUUID() };
|
|
79
|
+
try {
|
|
80
|
+
await filesystem.publishBytes(root, directory + '/owner.json', new TextEncoder().encode(JSON.stringify(value) + '\n'), { mode: 'exclusive' });
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
if (!occupied(error))
|
|
84
|
+
throw fail('PERSISTENCE_UNKNOWN');
|
|
85
|
+
}
|
|
86
|
+
marker = await markerBytes(markerFile);
|
|
87
|
+
}
|
|
88
|
+
if (!protocolRecord(marker, ['schemaVersion', 'root', 'directory', 'limits', 'ownerId']) || !publishingRequestId(marker.ownerId) || !isDeepStrictEqual({ ...marker, ownerId: undefined }, { ...context, ownerId: undefined }))
|
|
89
|
+
throw fail('CONTEXT_CHANGED');
|
|
90
|
+
const allowed = new Set(['owner.json', 'journal.sqlite', 'journal.sqlite-journal']);
|
|
91
|
+
let retained = 0;
|
|
92
|
+
for (const name of await fs.readdir(absolute)) {
|
|
93
|
+
if (!allowed.has(name))
|
|
94
|
+
throw fail('OCCUPIED');
|
|
95
|
+
const file = path.join(absolute, name), info = await fs.lstat(file);
|
|
96
|
+
if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || await fs.realpath(file) !== file)
|
|
97
|
+
throw fail('BOUNDARY');
|
|
98
|
+
retained += info.size;
|
|
99
|
+
}
|
|
100
|
+
if (retained > limits.maximumBytes * 2 + 65536)
|
|
101
|
+
throw fail('BYTE_LIMIT');
|
|
102
|
+
try {
|
|
103
|
+
await fs.lstat(databaseFile);
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
if (!fileMissing(error))
|
|
107
|
+
throw error;
|
|
108
|
+
try {
|
|
109
|
+
await filesystem.publishBytes(root, directory + '/journal.sqlite', new Uint8Array(), { mode: 'exclusive' });
|
|
110
|
+
}
|
|
111
|
+
catch (error) {
|
|
112
|
+
if (!occupied(error))
|
|
113
|
+
throw fail('PERSISTENCE_UNKNOWN');
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
signal?.throwIfAborted();
|
|
117
|
+
let opened;
|
|
118
|
+
try {
|
|
119
|
+
const database = opened = new DatabaseSync(databaseFile, { enableForeignKeyConstraints: true, enableDoubleQuotedStringLiterals: false, allowExtension: false });
|
|
120
|
+
const tables = database.prepare("SELECT name FROM sqlite_schema WHERE type='table' AND substr(name,1,7)<>'sqlite_' ORDER BY name").all().map(row => row.name);
|
|
121
|
+
if (tables.length === 0) {
|
|
122
|
+
database.exec('PRAGMA journal_mode=DELETE;PRAGMA synchronous=FULL;PRAGMA temp_store=MEMORY;');
|
|
123
|
+
database.exec('BEGIN IMMEDIATE');
|
|
124
|
+
try {
|
|
125
|
+
database.exec('CREATE TABLE journal_metadata (id INTEGER PRIMARY KEY CHECK(id=1),payload TEXT NOT NULL) STRICT;CREATE TABLE journal_records (key TEXT PRIMARY KEY,revision INTEGER NOT NULL CHECK(revision>0),payload TEXT NOT NULL) STRICT;CREATE TABLE journal_blobs (sha256 TEXT PRIMARY KEY,byte_length INTEGER NOT NULL CHECK(byte_length>=0),bytes BLOB NOT NULL) STRICT;');
|
|
126
|
+
database.prepare('INSERT INTO journal_metadata(id,payload) VALUES(1,?)').run(JSON.stringify(marker));
|
|
127
|
+
database.exec('COMMIT');
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
try {
|
|
131
|
+
database.exec('ROLLBACK');
|
|
132
|
+
}
|
|
133
|
+
catch { }
|
|
134
|
+
throw error;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
else if (tables.join(',') !== 'journal_blobs,journal_metadata,journal_records')
|
|
138
|
+
throw fail('OWNERSHIP_INVALID');
|
|
139
|
+
const stored = database.prepare('SELECT payload FROM journal_metadata WHERE id=1').get();
|
|
140
|
+
if (!stored || typeof stored.payload !== 'string' || !isDeepStrictEqual(JSON.parse(stored.payload), marker))
|
|
141
|
+
throw fail('OWNERSHIP_INVALID');
|
|
142
|
+
database.exec('PRAGMA journal_mode=DELETE;PRAGMA synchronous=FULL;PRAGMA foreign_keys=ON;PRAGMA trusted_schema=OFF;PRAGMA temp_store=MEMORY;PRAGMA busy_timeout=0;');
|
|
143
|
+
const pages = Math.floor(limits.maximumBytes / 4096);
|
|
144
|
+
database.exec('PRAGMA max_page_count=' + pages);
|
|
145
|
+
if (Number(database.prepare('PRAGMA page_size').get()?.page_size) !== 4096 || Number(database.prepare('PRAGMA max_page_count').get()?.max_page_count) !== pages)
|
|
146
|
+
throw fail('BYTE_LIMIT');
|
|
147
|
+
await filesystem.ensureDirectory(root, directory);
|
|
148
|
+
signal?.throwIfAborted();
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
try {
|
|
152
|
+
opened?.close();
|
|
153
|
+
}
|
|
154
|
+
catch { }
|
|
155
|
+
storageFailure(error);
|
|
156
|
+
}
|
|
157
|
+
if (!opened)
|
|
158
|
+
throw fail('STORAGE_UNKNOWN');
|
|
159
|
+
const database = opened;
|
|
160
|
+
let closed = false;
|
|
161
|
+
const ready = () => { if (closed)
|
|
162
|
+
throw fail('CLOSED'); };
|
|
163
|
+
const load = async (key, { signal } = {}) => {
|
|
164
|
+
ready();
|
|
165
|
+
signal?.throwIfAborted();
|
|
166
|
+
if (!keyValid(key))
|
|
167
|
+
throw fail('KEY_INVALID');
|
|
168
|
+
const row = database.prepare('SELECT revision,payload FROM journal_records WHERE key=?').get(key);
|
|
169
|
+
if (!row)
|
|
170
|
+
return undefined;
|
|
171
|
+
if (typeof row.revision !== 'number' || typeof row.payload !== 'string' || !Number.isSafeInteger(row.revision) || row.revision < 1 || recordBytes(key, row.revision, row.payload) > limits.maximumRecordBytes)
|
|
172
|
+
throw fail('RECORD_INVALID');
|
|
173
|
+
let payload;
|
|
174
|
+
try {
|
|
175
|
+
payload = JSON.parse(row.payload);
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
throw fail('RECORD_INVALID');
|
|
179
|
+
}
|
|
180
|
+
return { revision: row.revision, payload };
|
|
181
|
+
};
|
|
182
|
+
const readBlob = async ({ sha256, byteLength }, { signal } = {}) => {
|
|
183
|
+
ready();
|
|
184
|
+
signal?.throwIfAborted();
|
|
185
|
+
if (!publishingDigest(sha256) || !Number.isSafeInteger(byteLength) || byteLength < 0 || byteLength > limits.maximumBlobBytes)
|
|
186
|
+
throw fail('BLOB_INVALID');
|
|
187
|
+
const row = database.prepare('SELECT byte_length,bytes FROM journal_blobs WHERE sha256=?').get(sha256);
|
|
188
|
+
if (!row)
|
|
189
|
+
return undefined;
|
|
190
|
+
if (row.byte_length !== byteLength || !(row.bytes instanceof Uint8Array) || row.bytes.byteLength !== byteLength || createHash('sha256').update(row.bytes).digest('hex') !== sha256)
|
|
191
|
+
throw fail('BLOB_INVALID');
|
|
192
|
+
return new Uint8Array(row.bytes);
|
|
193
|
+
};
|
|
194
|
+
const compareAndSet = async ({ key, expectedRevision, payload, blobs = [] }, { signal } = {}) => {
|
|
195
|
+
ready();
|
|
196
|
+
signal?.throwIfAborted();
|
|
197
|
+
if (!keyValid(key) || !Number.isSafeInteger(expectedRevision) || expectedRevision < 0 || expectedRevision === Number.MAX_SAFE_INTEGER)
|
|
198
|
+
throw fail('RECORD_INVALID');
|
|
199
|
+
let encoded;
|
|
200
|
+
try {
|
|
201
|
+
encoded = JSON.stringify(payload);
|
|
202
|
+
}
|
|
203
|
+
catch {
|
|
204
|
+
throw fail('RECORD_INVALID');
|
|
205
|
+
}
|
|
206
|
+
if (typeof encoded !== 'string')
|
|
207
|
+
throw fail('RECORD_INVALID');
|
|
208
|
+
if (recordBytes(key, expectedRevision + 1, encoded) > limits.maximumRecordBytes)
|
|
209
|
+
throw fail('BYTE_LIMIT');
|
|
210
|
+
if (!Array.isArray(blobs) || blobs.length > limits.maximumBlobs)
|
|
211
|
+
throw fail('BLOB_LIMIT');
|
|
212
|
+
const snapshots = [];
|
|
213
|
+
let blobBytes = 0;
|
|
214
|
+
for (const blob of blobs) {
|
|
215
|
+
if (!protocolRecord(blob, ['sha256', 'bytes']) || !publishingDigest(blob.sha256) || !(blob.bytes instanceof Uint8Array) || blob.bytes.byteLength > limits.maximumBlobBytes)
|
|
216
|
+
throw fail('BLOB_INVALID');
|
|
217
|
+
blobBytes += blob.bytes.byteLength;
|
|
218
|
+
if (blobBytes > limits.maximumBytes)
|
|
219
|
+
throw fail('BYTE_LIMIT');
|
|
220
|
+
const bytes = new Uint8Array(blob.bytes);
|
|
221
|
+
if (createHash('sha256').update(bytes).digest('hex') !== blob.sha256)
|
|
222
|
+
throw fail('BLOB_INVALID');
|
|
223
|
+
snapshots.push({ sha256: blob.sha256, bytes });
|
|
224
|
+
}
|
|
225
|
+
await capacity(root, limits);
|
|
226
|
+
ready();
|
|
227
|
+
signal?.throwIfAborted();
|
|
228
|
+
try {
|
|
229
|
+
database.exec('BEGIN IMMEDIATE');
|
|
230
|
+
}
|
|
231
|
+
catch (error) {
|
|
232
|
+
storageFailure(error);
|
|
233
|
+
}
|
|
234
|
+
try {
|
|
235
|
+
const row = database.prepare('SELECT revision FROM journal_records WHERE key=?').get(key);
|
|
236
|
+
if ((row?.revision ?? 0) !== expectedRevision) {
|
|
237
|
+
database.exec('ROLLBACK');
|
|
238
|
+
return 'conflict';
|
|
239
|
+
}
|
|
240
|
+
if (!row && Number(database.prepare('SELECT count(*) AS amount FROM journal_records').get()?.amount) >= limits.maximumRecords)
|
|
241
|
+
throw fail('RECORD_LIMIT');
|
|
242
|
+
for (const blob of snapshots) {
|
|
243
|
+
const existing = database.prepare('SELECT byte_length,bytes FROM journal_blobs WHERE sha256=?').get(blob.sha256);
|
|
244
|
+
if (existing) {
|
|
245
|
+
if (existing.byte_length !== blob.bytes.byteLength || !(existing.bytes instanceof Uint8Array) || !Buffer.from(existing.bytes).equals(blob.bytes))
|
|
246
|
+
throw fail('BLOB_INVALID');
|
|
247
|
+
}
|
|
248
|
+
else
|
|
249
|
+
database.prepare('INSERT INTO journal_blobs(sha256,byte_length,bytes) VALUES(?,?,?)').run(blob.sha256, blob.bytes.byteLength, blob.bytes);
|
|
250
|
+
}
|
|
251
|
+
if (Number(database.prepare('SELECT count(*) AS amount FROM journal_blobs').get()?.amount) > limits.maximumBlobs)
|
|
252
|
+
throw fail('BLOB_LIMIT');
|
|
253
|
+
database.prepare('INSERT INTO journal_records(key,revision,payload) VALUES(?,?,?) ON CONFLICT(key) DO UPDATE SET revision=excluded.revision,payload=excluded.payload').run(key, expectedRevision + 1, encoded);
|
|
254
|
+
database.exec('COMMIT');
|
|
255
|
+
return 'stored';
|
|
256
|
+
}
|
|
257
|
+
catch (error) {
|
|
258
|
+
try {
|
|
259
|
+
database.exec('ROLLBACK');
|
|
260
|
+
}
|
|
261
|
+
catch { }
|
|
262
|
+
storageFailure(error);
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
return Object.freeze({
|
|
266
|
+
load, readBlob, compareAndSet,
|
|
267
|
+
operationJournal() {
|
|
268
|
+
return {
|
|
269
|
+
async load(requestId, context) { if (!keyValid(requestId))
|
|
270
|
+
throw fail('KEY_INVALID'); return operationRecord(await load('operation:' + requestId, context), () => fail('RECORD_INVALID')); },
|
|
271
|
+
async compareAndSet({ expectedRevision, next }, context) { if (!next?.binding || !keyValid(next.binding.requestId) || next.revision !== expectedRevision + 1)
|
|
272
|
+
throw fail('RECORD_INVALID'); return compareAndSet({ key: 'operation:' + next.binding.requestId, expectedRevision, payload: jsonSnapshot(next) }, context); },
|
|
273
|
+
};
|
|
274
|
+
},
|
|
275
|
+
close() { if (!closed) {
|
|
276
|
+
database.close();
|
|
277
|
+
closed = true;
|
|
278
|
+
} },
|
|
279
|
+
});
|
|
280
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export declare function isAbsoluteLocalFile(value: string): boolean;
|
|
2
|
+
/** Read the named regular file once. A link, replacement or size change never selects a different JSON document. */
|
|
3
|
+
export declare function readLocalJsonFile(file: string, maximumBytes: number, signal?: AbortSignal): Promise<unknown>;
|