@ankhorage/projects 0.7.2 → 0.8.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 +19 -12
- package/dist/capabilities/index.d.ts +330 -0
- package/dist/capabilities/index.js +194 -0
- package/dist/capabilities/socialManagerMediaAnalytics.d.ts +92 -0
- package/dist/capabilities/socialManagerMediaAnalytics.js +75 -0
- package/dist/features/projects/composition/composeGeneratedRuntimeMaterialization.d.ts +1 -0
- package/dist/features/projects/composition/composeGeneratedRuntimeMaterialization.js +13 -5
- package/dist/features/projects/composition/createExpoProjectMaterializer.js +27 -23
- package/dist/features/projects/composition/createRootNavigatorGenerationOptions.d.ts +9 -0
- package/dist/features/projects/composition/createRootNavigatorGenerationOptions.js +10 -0
- package/dist/features/projects/composition/createSocialManagerServerFiles.d.ts +6 -0
- package/dist/features/projects/composition/createSocialManagerServerFiles.js +16 -0
- package/dist/features/trusted-social-manager-host/adapters/createConnectionFileSystemRepositories.d.ts +16 -0
- package/dist/features/trusted-social-manager-host/adapters/createConnectionFileSystemRepositories.js +201 -0
- package/dist/features/trusted-social-manager-host/adapters/createConnectionFileSystemStoreAsync.d.ts +25 -0
- package/dist/features/trusted-social-manager-host/adapters/createConnectionFileSystemStoreAsync.js +72 -0
- package/dist/features/trusted-social-manager-host/adapters/createSocialManagerDraftStoreAsync.d.ts +7 -0
- package/dist/features/trusted-social-manager-host/adapters/createSocialManagerDraftStoreAsync.js +160 -0
- package/dist/features/trusted-social-manager-host/adapters/createSocialManagerFlowSecurityAsync.d.ts +19 -0
- package/dist/features/trusted-social-manager-host/adapters/createSocialManagerFlowSecurityAsync.js +176 -0
- package/dist/features/trusted-social-manager-host/adapters/createSocialManagerMediaPreflight.d.ts +4 -0
- package/dist/features/trusted-social-manager-host/adapters/createSocialManagerMediaPreflight.js +37 -0
- package/dist/features/trusted-social-manager-host/adapters/createSocialManagerMediaStoreAsync.d.ts +7 -0
- package/dist/features/trusted-social-manager-host/adapters/createSocialManagerMediaStoreAsync.js +242 -0
- package/dist/features/trusted-social-manager-host/adapters/createSocialOperationStoresAsync.d.ts +13 -0
- package/dist/features/trusted-social-manager-host/adapters/createSocialOperationStoresAsync.js +244 -0
- package/dist/features/trusted-social-manager-host/adapters/projectSocialManagerConnection.d.ts +53 -0
- package/dist/features/trusted-social-manager-host/adapters/projectSocialManagerConnection.js +42 -0
- package/dist/features/trusted-social-manager-host/application/createSocialManagerPublicationRuntime.d.ts +10 -0
- package/dist/features/trusted-social-manager-host/application/createSocialManagerPublicationRuntime.js +240 -0
- package/dist/features/trusted-social-manager-host/application/resolveSocialManagerPublication.d.ts +22 -0
- package/dist/features/trusted-social-manager-host/application/resolveSocialManagerPublication.js +97 -0
- package/dist/features/trusted-social-manager-host/composition/createSocialManagerCapabilityOperations.d.ts +22 -0
- package/dist/features/trusted-social-manager-host/composition/createSocialManagerCapabilityOperations.js +224 -0
- package/dist/features/trusted-social-manager-host/composition/createSocialManagerConnectionOperations.d.ts +20 -0
- package/dist/features/trusted-social-manager-host/composition/createSocialManagerConnectionOperations.js +152 -0
- package/dist/features/trusted-social-manager-host/composition/createSocialManagerLocalProviderFixtures.d.ts +22 -0
- package/dist/features/trusted-social-manager-host/composition/createSocialManagerLocalProviderFixtures.js +271 -0
- package/dist/features/trusted-social-manager-host/composition/createSocialManagerMediaOperations.d.ts +14 -0
- package/dist/features/trusted-social-manager-host/composition/createSocialManagerMediaOperations.js +72 -0
- package/dist/features/trusted-social-manager-host/composition/createSocialManagerProvider.d.ts +20 -0
- package/dist/features/trusted-social-manager-host/composition/createSocialManagerProvider.js +20 -0
- package/dist/features/trusted-social-manager-host/composition/createSocialManagerPublicationOperations.d.ts +15 -0
- package/dist/features/trusted-social-manager-host/composition/createSocialManagerPublicationOperations.js +185 -0
- package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerFileSystemPersistenceAsync.d.ts +14 -0
- package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerFileSystemPersistenceAsync.js +17 -0
- package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerHost.d.ts +51 -0
- package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerHost.js +188 -0
- package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerLocalHostAsync.d.ts +18 -0
- package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerLocalHostAsync.js +177 -0
- package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerLocalServerAsync.d.ts +26 -0
- package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerLocalServerAsync.js +66 -0
- package/dist/features/trusted-social-manager-host/domain/publicationConfig.d.ts +18 -0
- package/dist/features/trusted-social-manager-host/domain/publicationConfig.js +77 -0
- package/dist/features/trusted-social-manager-host/domain/readSocialManagerConnectionRequest.d.ts +54 -0
- package/dist/features/trusted-social-manager-host/domain/readSocialManagerConnectionRequest.js +77 -0
- package/dist/features/trusted-social-manager-host/domain/readSocialManagerDraftContent.d.ts +3 -0
- package/dist/features/trusted-social-manager-host/domain/readSocialManagerDraftContent.js +47 -0
- package/dist/features/trusted-social-manager-host/domain/socialManagerConnectionIdentity.d.ts +17 -0
- package/dist/features/trusted-social-manager-host/domain/socialManagerConnectionIdentity.js +17 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +14 -0
- package/dist/types/socialManager.d.ts +77 -0
- package/dist/types/socialManager.js +1 -0
- package/dist/types/socialManagerPublication.d.ts +27 -0
- package/dist/types/socialManagerPublication.js +1 -0
- package/package.json +507 -9
package/dist/features/trusted-social-manager-host/adapters/createSocialManagerDraftStoreAsync.js
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { constants, lstat, mkdir, open } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { createKeyedAsyncMutex } from '@ankhorage/utility/concurrency';
|
|
5
|
+
import { isMissingPathError, writeJsonFileAtomic } from '@ankhorage/utility/node/fs';
|
|
6
|
+
import { isRecord } from '@ankhorage/utility/object';
|
|
7
|
+
import { readSocialManagerDraftContent } from '../domain/readSocialManagerDraftContent.js';
|
|
8
|
+
/***
|
|
9
|
+
* Persist immutable draft revisions for one local development host.
|
|
10
|
+
* The configured directory must be private and trusted. Assign it to one writer
|
|
11
|
+
* process and one adapter instance; this is not a distributed database adapter.
|
|
12
|
+
*/
|
|
13
|
+
export async function createSocialManagerDraftStoreAsync(directory) {
|
|
14
|
+
const root = join(directory, 'social-manager-drafts');
|
|
15
|
+
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
16
|
+
const stat = await lstat(root);
|
|
17
|
+
if (!stat.isDirectory() || (stat.mode & 0o077) !== 0) {
|
|
18
|
+
throw new Error('Social Manager draft directory must be private.');
|
|
19
|
+
}
|
|
20
|
+
const mutations = createKeyedAsyncMutex();
|
|
21
|
+
return {
|
|
22
|
+
createAsync: async (scope, content) => {
|
|
23
|
+
const key = scopeKey(scope);
|
|
24
|
+
return mutations.run(key, () => createDraftAsync(root, key, content));
|
|
25
|
+
},
|
|
26
|
+
listAsync: async (scope) => {
|
|
27
|
+
const records = await readRevisionsAsync(root, scopeKey(scope));
|
|
28
|
+
return Array.from(new Map(records.map((record) => [record.id, record])).values());
|
|
29
|
+
},
|
|
30
|
+
readAsync: async (scope, id, revision) => {
|
|
31
|
+
const records = await readRevisionsAsync(root, scopeKey(scope));
|
|
32
|
+
return records
|
|
33
|
+
.filter((record) => record.id === id && (revision === undefined || record.revision === revision))
|
|
34
|
+
.at(-1);
|
|
35
|
+
},
|
|
36
|
+
updateAsync: async (scope, id, expectedRevision, content) => {
|
|
37
|
+
const key = scopeKey(scope);
|
|
38
|
+
return mutations.run(key, () => updateDraftAsync(root, key, id, expectedRevision, content));
|
|
39
|
+
},
|
|
40
|
+
isMediaReferencedAsync: async (scope, mediaId) => readRevisionsAsync(root, scopeKey(scope)).then((records) => records.some((record) => hasMediaReference(record.content, mediaId))),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/*** Append the first immutable revision within the serialized scope mutation. */
|
|
44
|
+
async function createDraftAsync(root, key, content) {
|
|
45
|
+
const records = await readRevisionsAsync(root, key);
|
|
46
|
+
const now = new Date().toISOString();
|
|
47
|
+
const draft = {
|
|
48
|
+
id: randomUUID(),
|
|
49
|
+
revision: 1,
|
|
50
|
+
createdAt: now,
|
|
51
|
+
updatedAt: now,
|
|
52
|
+
content: requireContent(content),
|
|
53
|
+
};
|
|
54
|
+
await saveRevisionsAsync(root, key, [...records, draft]);
|
|
55
|
+
return draft;
|
|
56
|
+
}
|
|
57
|
+
/*** Append an edit only when the caller's expected revision is still current. */
|
|
58
|
+
async function updateDraftAsync(root, key, id, expectedRevision, content) {
|
|
59
|
+
const records = await readRevisionsAsync(root, key);
|
|
60
|
+
const current = records.filter((record) => record.id === id).at(-1);
|
|
61
|
+
if (!current)
|
|
62
|
+
return { status: 'not-found' };
|
|
63
|
+
if (current.revision !== expectedRevision)
|
|
64
|
+
return { status: 'conflict' };
|
|
65
|
+
const draft = {
|
|
66
|
+
...current,
|
|
67
|
+
revision: current.revision + 1,
|
|
68
|
+
updatedAt: new Date().toISOString(),
|
|
69
|
+
content: requireContent(content),
|
|
70
|
+
};
|
|
71
|
+
await saveRevisionsAsync(root, key, [...records, draft]);
|
|
72
|
+
return { status: 'updated', draft };
|
|
73
|
+
}
|
|
74
|
+
/*** Derive a filesystem-safe scope identity without using caller-controlled path segments. */
|
|
75
|
+
function scopeKey(scope) {
|
|
76
|
+
const values = [scope.tenantId, scope.projectId, scope.environmentId];
|
|
77
|
+
if (values.some((value) => !value.trim()))
|
|
78
|
+
throw new Error('Social Manager scope is incomplete.');
|
|
79
|
+
return createHash('sha256').update(JSON.stringify(values)).digest('hex');
|
|
80
|
+
}
|
|
81
|
+
/*** Reject malformed draft content before it can be persisted. */
|
|
82
|
+
function requireContent(content) {
|
|
83
|
+
const parsed = readSocialManagerDraftContent(content);
|
|
84
|
+
if (!parsed)
|
|
85
|
+
throw new Error('Invalid Social Manager draft content.');
|
|
86
|
+
return parsed;
|
|
87
|
+
}
|
|
88
|
+
/*** Read an entire atomic scope document and fail closed on invalid persisted revisions. */
|
|
89
|
+
async function readRevisionsAsync(root, key) {
|
|
90
|
+
const path = join(root, `${key}.json`);
|
|
91
|
+
try {
|
|
92
|
+
const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
93
|
+
try {
|
|
94
|
+
if (!(await handle.stat()).isFile())
|
|
95
|
+
throw new Error('Invalid Social Manager draft file.');
|
|
96
|
+
const value = JSON.parse(await handle.readFile('utf8'));
|
|
97
|
+
if (!isRecord(value) || value.scope !== key || !Array.isArray(value.revisions)) {
|
|
98
|
+
throw new Error('Invalid Social Manager draft document.');
|
|
99
|
+
}
|
|
100
|
+
const records = value.revisions.map(readRevision);
|
|
101
|
+
if (!records.every((record) => record !== undefined) || !hasSequentialRevisions(records)) {
|
|
102
|
+
throw new Error('Invalid Social Manager draft revisions.');
|
|
103
|
+
}
|
|
104
|
+
return records;
|
|
105
|
+
}
|
|
106
|
+
finally {
|
|
107
|
+
await handle.close();
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
if (isMissingPathError(error))
|
|
112
|
+
return [];
|
|
113
|
+
throw error;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/*** Validate every revision before returning any application data from persistence. */
|
|
117
|
+
function readRevision(value) {
|
|
118
|
+
if (!isRecord(value) ||
|
|
119
|
+
typeof value.id !== 'string' ||
|
|
120
|
+
!value.id.trim() ||
|
|
121
|
+
typeof value.revision !== 'number' ||
|
|
122
|
+
!Number.isSafeInteger(value.revision) ||
|
|
123
|
+
value.revision < 1 ||
|
|
124
|
+
typeof value.createdAt !== 'string' ||
|
|
125
|
+
typeof value.updatedAt !== 'string') {
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
const content = readSocialManagerDraftContent(value.content);
|
|
129
|
+
return content
|
|
130
|
+
? {
|
|
131
|
+
id: value.id,
|
|
132
|
+
revision: value.revision,
|
|
133
|
+
createdAt: value.createdAt,
|
|
134
|
+
updatedAt: value.updatedAt,
|
|
135
|
+
content,
|
|
136
|
+
}
|
|
137
|
+
: undefined;
|
|
138
|
+
}
|
|
139
|
+
/*** Verify an append-only revision sequence independently for every stored draft. */
|
|
140
|
+
function hasSequentialRevisions(records) {
|
|
141
|
+
const previous = new Map();
|
|
142
|
+
return records.every((record) => {
|
|
143
|
+
const prior = previous.get(record.id);
|
|
144
|
+
if (record.revision !== (prior?.revision ?? 0) + 1)
|
|
145
|
+
return false;
|
|
146
|
+
if (prior && prior.createdAt !== record.createdAt)
|
|
147
|
+
return false;
|
|
148
|
+
previous.set(record.id, record);
|
|
149
|
+
return true;
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
/*** Preserve media referenced by any immutable draft revision, including already approved revisions. */
|
|
153
|
+
function hasMediaReference(content, mediaId) {
|
|
154
|
+
return (content.mediaIds.includes(mediaId) ||
|
|
155
|
+
content.destinations.some((destination) => destination.mediaIds.includes(mediaId)));
|
|
156
|
+
}
|
|
157
|
+
/*** Atomically persist all revisions under the server-owned scope. */
|
|
158
|
+
async function saveRevisionsAsync(root, key, revisions) {
|
|
159
|
+
await writeJsonFileAtomic(join(root, `${key}.json`), { scope: key, revisions });
|
|
160
|
+
}
|
package/dist/features/trusted-social-manager-host/adapters/createSocialManagerFlowSecurityAsync.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { SecretStoreAdapter } from '@ankhorage/contracts/secrets';
|
|
2
|
+
import { type FlowRateLimitPort, type FlowRuntimeStorePort, type FlowSecurityAuditPort, type FlowSecurityGrant, type FlowSecurityPort } from '@ankhorage/flow';
|
|
3
|
+
export type CreateSocialManagerFlowSecurityInput = Readonly<{
|
|
4
|
+
scope: Readonly<{
|
|
5
|
+
tenantId: string;
|
|
6
|
+
projectId: string;
|
|
7
|
+
environmentId: string;
|
|
8
|
+
}>;
|
|
9
|
+
store: FlowRuntimeStorePort;
|
|
10
|
+
grants: readonly FlowSecurityGrant[];
|
|
11
|
+
audit: FlowSecurityAuditPort;
|
|
12
|
+
rateLimit: FlowRateLimitPort;
|
|
13
|
+
secretStore: SecretStoreAdapter;
|
|
14
|
+
}>;
|
|
15
|
+
/***
|
|
16
|
+
* Compose Flow's canonical permit boundary with host-owned durable publication approvals and claims.
|
|
17
|
+
* Approval lookup derives the exact operation identity from the immutable Flow revision.
|
|
18
|
+
*/
|
|
19
|
+
export declare function createSocialManagerFlowSecurityAsync(directory: string, input: CreateSocialManagerFlowSecurityInput): Promise<FlowSecurityPort>;
|
package/dist/features/trusted-social-manager-host/adapters/createSocialManagerFlowSecurityAsync.js
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { constants, lstat, mkdir, open } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { createFlowSecurityPort, } from '@ankhorage/flow';
|
|
5
|
+
import { isMissingPathError, writeJsonFileAtomic } from '@ankhorage/utility/node/fs';
|
|
6
|
+
import { isRecord } from '@ankhorage/utility/object';
|
|
7
|
+
import { readPublicationConfig } from '../domain/publicationConfig.js';
|
|
8
|
+
const publicationCapability = 'projects.social.publication.execute';
|
|
9
|
+
const publicationStep = ':step:publication';
|
|
10
|
+
/***
|
|
11
|
+
* Compose Flow's canonical permit boundary with host-owned durable publication approvals and claims.
|
|
12
|
+
* Approval lookup derives the exact operation identity from the immutable Flow revision.
|
|
13
|
+
*/
|
|
14
|
+
export async function createSocialManagerFlowSecurityAsync(directory, input) {
|
|
15
|
+
const root = join(directory, 'social-flow-security');
|
|
16
|
+
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
17
|
+
const stat = await lstat(root);
|
|
18
|
+
if (!stat.isDirectory() || (stat.mode & 0o077) !== 0)
|
|
19
|
+
throw new Error('Social Flow security directory must be private.');
|
|
20
|
+
return createFlowSecurityPort({
|
|
21
|
+
approvalStore: createApprovalStore(input),
|
|
22
|
+
operationStore: createOperationStore(root),
|
|
23
|
+
grants: input.grants,
|
|
24
|
+
audit: input.audit,
|
|
25
|
+
rateLimit: input.rateLimit,
|
|
26
|
+
secretStore: input.secretStore,
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
/*** Resolve an approval only when its Flow run and immutable publication node match the full permit. */
|
|
30
|
+
function createApprovalStore(input) {
|
|
31
|
+
return {
|
|
32
|
+
getAsync: async (operation) => {
|
|
33
|
+
const runId = runIdOf(operation);
|
|
34
|
+
if (!runId)
|
|
35
|
+
return undefined;
|
|
36
|
+
const scope = { tenantId: operation.actor.tenantId, projectId: operation.actor.projectId };
|
|
37
|
+
const run = await input.store.getRunAsync(scope, runId);
|
|
38
|
+
if (!run)
|
|
39
|
+
return undefined;
|
|
40
|
+
const workflow = await input.store.getWorkflowAsync(scope, run.flow.id, run.flow.version);
|
|
41
|
+
const node = workflow?.definition.nodes.find((candidate) => candidate.id === 'publication');
|
|
42
|
+
if (!node?.config || !samePublicationIdentity(operation, input.scope, node, run.id))
|
|
43
|
+
return undefined;
|
|
44
|
+
const approval = await input.store.getApprovalAsync(scope, `social-approval:${run.id}`);
|
|
45
|
+
if (approval?.runId !== run.id)
|
|
46
|
+
return undefined;
|
|
47
|
+
return {
|
|
48
|
+
operation,
|
|
49
|
+
status: approval.status === 'approved' || approval.status === 'pending'
|
|
50
|
+
? approval.status
|
|
51
|
+
: 'rejected',
|
|
52
|
+
};
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
/*** Create an atomic single-process durable permit claim store keyed by the complete Flow identity. */
|
|
57
|
+
function createOperationStore(root) {
|
|
58
|
+
const mutation = createMutationAsync(root);
|
|
59
|
+
return {
|
|
60
|
+
claimAsync: (operation) => mutation((document) => {
|
|
61
|
+
const key = operationKey(operation);
|
|
62
|
+
if (operationState(document, key) !== undefined)
|
|
63
|
+
return [document, false];
|
|
64
|
+
return [replaceOperationState(document, key, 'claimed'), true];
|
|
65
|
+
}),
|
|
66
|
+
consumeAsync: (operation) => mutation((document) => {
|
|
67
|
+
const key = operationKey(operation);
|
|
68
|
+
if (operationState(document, key) !== 'claimed')
|
|
69
|
+
return [document, false];
|
|
70
|
+
return [replaceOperationState(document, key, 'consumed'), true];
|
|
71
|
+
}),
|
|
72
|
+
releaseAsync: (operation) => mutation((document) => {
|
|
73
|
+
const key = operationKey(operation);
|
|
74
|
+
if (operationState(document, key) !== 'claimed')
|
|
75
|
+
return [document, undefined];
|
|
76
|
+
return [removeOperationState(document, key), undefined];
|
|
77
|
+
}),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
/*** Serialize document updates so claim, consumption, and release cannot interleave in one host. */
|
|
81
|
+
function createMutationAsync(root) {
|
|
82
|
+
let tail = Promise.resolve();
|
|
83
|
+
return async (operation) => {
|
|
84
|
+
const previous = tail;
|
|
85
|
+
let release = () => undefined;
|
|
86
|
+
tail = new Promise((resolve) => {
|
|
87
|
+
release = resolve;
|
|
88
|
+
});
|
|
89
|
+
await previous;
|
|
90
|
+
try {
|
|
91
|
+
const [next, value] = await operation(await readDocumentAsync(root));
|
|
92
|
+
await writeJsonFileAtomic(join(root, 'operations.json'), next);
|
|
93
|
+
return value;
|
|
94
|
+
}
|
|
95
|
+
finally {
|
|
96
|
+
release();
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
/*** Read and validate the security claim document without following an attacker-controlled symlink. */
|
|
101
|
+
async function readDocumentAsync(root) {
|
|
102
|
+
try {
|
|
103
|
+
const handle = await open(join(root, 'operations.json'), constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
104
|
+
try {
|
|
105
|
+
if (!(await handle.stat()).isFile())
|
|
106
|
+
throw new Error('Social Flow security state is not a file.');
|
|
107
|
+
const value = JSON.parse(await handle.readFile('utf8'));
|
|
108
|
+
if (!isOperationDocument(value))
|
|
109
|
+
throw new Error('Social Flow security state is invalid.');
|
|
110
|
+
return value;
|
|
111
|
+
}
|
|
112
|
+
finally {
|
|
113
|
+
await handle.close();
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
if (isMissingPathError(error))
|
|
118
|
+
return { version: 1, operations: {} };
|
|
119
|
+
throw error;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/*** Reject malformed claim state before it can weaken exact-once publication semantics. */
|
|
123
|
+
function isOperationDocument(value) {
|
|
124
|
+
return (isRecord(value) &&
|
|
125
|
+
value.version === 1 &&
|
|
126
|
+
isRecord(value.operations) &&
|
|
127
|
+
Object.values(value.operations).every((state) => state === 'claimed' || state === 'consumed'));
|
|
128
|
+
}
|
|
129
|
+
/*** Require the durable work key to identify the exact publication step for one Flow run. */
|
|
130
|
+
function runIdOf(operation) {
|
|
131
|
+
if (operation.capability !== publicationCapability ||
|
|
132
|
+
operation.operationId !== operation.idempotencyKey ||
|
|
133
|
+
!operation.operationId.endsWith(publicationStep))
|
|
134
|
+
return undefined;
|
|
135
|
+
const runId = operation.operationId.slice(0, -publicationStep.length);
|
|
136
|
+
return runId.trim() ? runId : undefined;
|
|
137
|
+
}
|
|
138
|
+
/*** Bind approval lookup to caller scope, immutable publication configuration, and exact work identity. */
|
|
139
|
+
function samePublicationIdentity(operation, scope, node, runId) {
|
|
140
|
+
try {
|
|
141
|
+
const config = readPublicationConfig(node, scope);
|
|
142
|
+
return (runIdOf(operation) === runId &&
|
|
143
|
+
operation.actor.id === config.caller.actorId &&
|
|
144
|
+
operation.actor.tenantId === config.caller.tenantId &&
|
|
145
|
+
operation.actor.projectId === config.caller.projectId &&
|
|
146
|
+
operation.actor.environment === config.caller.environmentId);
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
return false;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/*** Hash every security-relevant field so a claim cannot be reused for a different operation identity. */
|
|
153
|
+
function operationKey(operation) {
|
|
154
|
+
return createHash('sha256').update(JSON.stringify(operation)).digest('hex');
|
|
155
|
+
}
|
|
156
|
+
/*** Read an exact persisted claim state without allowing arbitrary object-property access. */
|
|
157
|
+
function operationState(document, key) {
|
|
158
|
+
return Object.entries(document.operations).find(([candidate]) => candidate === key)?.[1];
|
|
159
|
+
}
|
|
160
|
+
/*** Replace one exact claim state while retaining every unrelated durable operation record. */
|
|
161
|
+
function replaceOperationState(document, key, state) {
|
|
162
|
+
return {
|
|
163
|
+
...document,
|
|
164
|
+
operations: Object.fromEntries([
|
|
165
|
+
...Object.entries(document.operations).filter(([candidate]) => candidate !== key),
|
|
166
|
+
[key, state],
|
|
167
|
+
]),
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
/*** Remove only an unconsumed claim so a retry may obtain a fresh permit for the same identity. */
|
|
171
|
+
function removeOperationState(document, key) {
|
|
172
|
+
return {
|
|
173
|
+
...document,
|
|
174
|
+
operations: Object.fromEntries(Object.entries(document.operations).filter(([candidate]) => candidate !== key)),
|
|
175
|
+
};
|
|
176
|
+
}
|
package/dist/features/trusted-social-manager-host/adapters/createSocialManagerMediaPreflight.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { SocialActionCommand, SocialMediaPreflightPort, SocialProviderCapability } from '@ankhorage/social';
|
|
2
|
+
import type { SocialManagerMediaStore } from '../../../types/socialManager.js';
|
|
3
|
+
/*** Build provider-capability media validation from immutable host-owned media metadata. */
|
|
4
|
+
export declare function createSocialManagerMediaPreflight(media: SocialManagerMediaStore, getCapabilityAsync: (command: SocialActionCommand) => Promise<SocialProviderCapability | null>): SocialMediaPreflightPort;
|
package/dist/features/trusted-social-manager-host/adapters/createSocialManagerMediaPreflight.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/*** Build provider-capability media validation from immutable host-owned media metadata. */
|
|
2
|
+
export function createSocialManagerMediaPreflight(media, getCapabilityAsync) {
|
|
3
|
+
return {
|
|
4
|
+
preflightAsync: async (command, references) => {
|
|
5
|
+
const capability = await getCapabilityAsync(command);
|
|
6
|
+
if (!capability?.enabled || !capability.publishingAllowed)
|
|
7
|
+
return rejected('social-provider-capability-unavailable');
|
|
8
|
+
if (capability.maxMediaItems !== undefined && references.length > capability.maxMediaItems)
|
|
9
|
+
return rejected('social-media-item-limit-exceeded');
|
|
10
|
+
const persisted = await Promise.all(references.map((reference) => media
|
|
11
|
+
.readForPublicationAsync({
|
|
12
|
+
tenantId: command.tenantId,
|
|
13
|
+
actorId: command.actorId,
|
|
14
|
+
mediaId: reference.mediaId,
|
|
15
|
+
})
|
|
16
|
+
.then((stored) => ({ reference, stored }))));
|
|
17
|
+
if (persisted.some(({ reference, stored }) => stored?.kind !== reference.kind ||
|
|
18
|
+
stored.contentType !== reference.contentType ||
|
|
19
|
+
stored.byteLength !== reference.byteLength)) {
|
|
20
|
+
return rejected('social-media-reference-unavailable');
|
|
21
|
+
}
|
|
22
|
+
return references.every((reference) => supportsMedia(capability, reference))
|
|
23
|
+
? { accepted: true }
|
|
24
|
+
: rejected('social-media-unsupported-by-provider');
|
|
25
|
+
},
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
/*** Check the exact kind, content type, and byte size declared by the current provider capability. */
|
|
29
|
+
function supportsMedia(capability, media) {
|
|
30
|
+
return capability.media.some((supported) => supported.kind === media.kind &&
|
|
31
|
+
supported.contentTypes.includes(media.contentType) &&
|
|
32
|
+
media.byteLength <= supported.maxByteLength);
|
|
33
|
+
}
|
|
34
|
+
/*** Keep rejected media results explicit without exposing trusted storage details. */
|
|
35
|
+
function rejected(code) {
|
|
36
|
+
return { accepted: false, diagnostic: { code } };
|
|
37
|
+
}
|
package/dist/features/trusted-social-manager-host/adapters/createSocialManagerMediaStoreAsync.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { SocialManagerMediaStore } from '../../../types/socialManager.js';
|
|
2
|
+
/***
|
|
3
|
+
* Persist immutable caller-owned Social media for one private local host directory.
|
|
4
|
+
* Media identifiers contain both a server-derived scope hash and content hash, so they
|
|
5
|
+
* remain stable across restarts without making mutable filenames part of publication state.
|
|
6
|
+
*/
|
|
7
|
+
export declare function createSocialManagerMediaStoreAsync(directory: string): Promise<SocialManagerMediaStore>;
|
package/dist/features/trusted-social-manager-host/adapters/createSocialManagerMediaStoreAsync.js
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { constants, lstat, mkdir, open, rename, unlink, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { createKeyedAsyncMutex } from '@ankhorage/utility/concurrency';
|
|
5
|
+
import { isMissingPathError, writeJsonFileAtomic } from '@ankhorage/utility/node/fs';
|
|
6
|
+
import { isRecord } from '@ankhorage/utility/object';
|
|
7
|
+
const maximumByteLength = 2_000_000_000;
|
|
8
|
+
/***
|
|
9
|
+
* Persist immutable caller-owned Social media for one private local host directory.
|
|
10
|
+
* Media identifiers contain both a server-derived scope hash and content hash, so they
|
|
11
|
+
* remain stable across restarts without making mutable filenames part of publication state.
|
|
12
|
+
*/
|
|
13
|
+
export async function createSocialManagerMediaStoreAsync(directory) {
|
|
14
|
+
const root = join(directory, 'social-manager-media');
|
|
15
|
+
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
16
|
+
await requirePrivateDirectoryAsync(root, 'Social Manager media directory');
|
|
17
|
+
const mutations = createKeyedAsyncMutex();
|
|
18
|
+
return {
|
|
19
|
+
uploadAsync: async (caller, upload) => {
|
|
20
|
+
const key = callerKey(caller);
|
|
21
|
+
return mutations.run(key, () => uploadAsync(root, key, caller, upload));
|
|
22
|
+
},
|
|
23
|
+
listAsync: async (caller) => (await readDocumentAsync(root, callerKey(caller))).media.map(toMedia),
|
|
24
|
+
readAsync: async (caller, mediaId) => findMedia(await readDocumentAsync(root, callerKey(caller)), mediaId)
|
|
25
|
+
.map(toMedia)
|
|
26
|
+
.at(0),
|
|
27
|
+
loadAsync: async (caller, mediaId) => loadAsync(root, callerKey(caller), mediaId),
|
|
28
|
+
readForPublicationAsync: async ({ tenantId, actorId, mediaId }) => readForPublicationAsync(root, tenantId, actorId, mediaId),
|
|
29
|
+
removeAsync: async (caller, mediaId, isReferencedAsync) => {
|
|
30
|
+
const key = callerKey(caller);
|
|
31
|
+
return mutations.run(key, () => removeAsync(root, key, mediaId, isReferencedAsync));
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/*** Store a new content-addressed object or return the existing immutable record. */
|
|
36
|
+
async function uploadAsync(root, key, caller, upload) {
|
|
37
|
+
const content = readUpload(upload);
|
|
38
|
+
const document = await readDocumentAsync(root, key);
|
|
39
|
+
const mediaId = createMediaId(key, content.bytes);
|
|
40
|
+
const existing = findMedia(document, mediaId).at(0);
|
|
41
|
+
if (existing) {
|
|
42
|
+
if (existing.contentType !== content.contentType || existing.kind !== content.kind)
|
|
43
|
+
throw new Error('Social Manager media content metadata is immutable.');
|
|
44
|
+
return toMedia(existing);
|
|
45
|
+
}
|
|
46
|
+
const record = {
|
|
47
|
+
...content,
|
|
48
|
+
mediaId,
|
|
49
|
+
createdAt: new Date().toISOString(),
|
|
50
|
+
...caller,
|
|
51
|
+
};
|
|
52
|
+
const directory = mediaDirectory(root, key);
|
|
53
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
54
|
+
await requirePrivateDirectoryAsync(directory, 'Social Manager media scope directory');
|
|
55
|
+
await writeContentAtomicAsync(join(directory, `${mediaId}.bin`), content.bytes);
|
|
56
|
+
await saveDocumentAsync(root, key, { ...document, media: [...document.media, record] });
|
|
57
|
+
return toMedia(record);
|
|
58
|
+
}
|
|
59
|
+
/*** Load exact caller-scoped immutable bytes after validating the persisted metadata. */
|
|
60
|
+
async function loadAsync(root, key, mediaId) {
|
|
61
|
+
const record = findMedia(await readDocumentAsync(root, key), mediaId).at(0);
|
|
62
|
+
if (!record)
|
|
63
|
+
return undefined;
|
|
64
|
+
const bytes = await readContentAsync(join(mediaDirectory(root, key), `${mediaId}.bin`));
|
|
65
|
+
if (!bytes || createMediaId(key, bytes) !== mediaId || bytes.byteLength !== record.byteLength)
|
|
66
|
+
throw new Error('Social Manager media content is unavailable or has changed.');
|
|
67
|
+
return { media: toMedia(record), bytes };
|
|
68
|
+
}
|
|
69
|
+
/*** Resolve publication metadata only when the opaque reference still names its original actor. */
|
|
70
|
+
async function readForPublicationAsync(root, tenantId, actorId, mediaId) {
|
|
71
|
+
const key = scopeKeyFromMediaId(mediaId);
|
|
72
|
+
if (!key)
|
|
73
|
+
return undefined;
|
|
74
|
+
const record = findMedia(await readDocumentAsync(root, key), mediaId).at(0);
|
|
75
|
+
return record?.tenantId === tenantId && record.actorId === actorId ? toMedia(record) : undefined;
|
|
76
|
+
}
|
|
77
|
+
/*** Delete bytes only after the caller has proved no immutable draft revision retains the reference. */
|
|
78
|
+
async function removeAsync(root, key, mediaId, isReferencedAsync) {
|
|
79
|
+
const document = await readDocumentAsync(root, key);
|
|
80
|
+
const record = findMedia(document, mediaId).at(0);
|
|
81
|
+
if (!record)
|
|
82
|
+
return 'not-found';
|
|
83
|
+
if (await isReferencedAsync(toMedia(record)))
|
|
84
|
+
return 'referenced';
|
|
85
|
+
await saveDocumentAsync(root, key, {
|
|
86
|
+
...document,
|
|
87
|
+
media: document.media.filter((candidate) => candidate.mediaId !== mediaId),
|
|
88
|
+
});
|
|
89
|
+
await unlink(join(mediaDirectory(root, key), `${mediaId}.bin`)).catch((error) => {
|
|
90
|
+
if (!isMissingPathError(error))
|
|
91
|
+
throw error;
|
|
92
|
+
});
|
|
93
|
+
return 'removed';
|
|
94
|
+
}
|
|
95
|
+
/*** Validate the bounded binary upload shape before it can become durable application state. */
|
|
96
|
+
function readUpload(upload) {
|
|
97
|
+
const kind = mediaKind(upload.contentType);
|
|
98
|
+
if (!kind ||
|
|
99
|
+
!(upload.bytes instanceof Uint8Array) ||
|
|
100
|
+
upload.bytes.byteLength === 0 ||
|
|
101
|
+
upload.bytes.byteLength > maximumByteLength) {
|
|
102
|
+
throw new Error('Invalid Social Manager media upload.');
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
kind,
|
|
106
|
+
contentType: upload.contentType,
|
|
107
|
+
byteLength: upload.bytes.byteLength,
|
|
108
|
+
bytes: upload.bytes,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
/*** Classify only media forms accepted by at least one configured Social provider. */
|
|
112
|
+
function mediaKind(contentType) {
|
|
113
|
+
return ['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(contentType)
|
|
114
|
+
? 'image'
|
|
115
|
+
: ['video/mp4', 'video/quicktime'].includes(contentType)
|
|
116
|
+
? 'video'
|
|
117
|
+
: undefined;
|
|
118
|
+
}
|
|
119
|
+
/*** Derive a stable opaque reference from the trusted scope and immutable content bytes. */
|
|
120
|
+
function createMediaId(key, bytes) {
|
|
121
|
+
return `media-${key}-${createHash('sha256').update(bytes).digest('hex')}`;
|
|
122
|
+
}
|
|
123
|
+
/*** Accept only references generated by this adapter before using their embedded scope key. */
|
|
124
|
+
function scopeKeyFromMediaId(mediaId) {
|
|
125
|
+
const match = /^media-([a-f0-9]{64})-[a-f0-9]{64}$/.exec(mediaId);
|
|
126
|
+
return match?.[1];
|
|
127
|
+
}
|
|
128
|
+
/*** Keep scope filenames independent from all caller-controlled path segments. */
|
|
129
|
+
function callerKey(caller) {
|
|
130
|
+
const values = [caller.tenantId, caller.projectId, caller.environmentId, caller.actorId];
|
|
131
|
+
if (values.some((value) => !value.trim()))
|
|
132
|
+
throw new Error('Social Manager scope is incomplete.');
|
|
133
|
+
return createHash('sha256').update(JSON.stringify(values)).digest('hex');
|
|
134
|
+
}
|
|
135
|
+
/*** Read a private scope document and fail closed on malformed immutable media records. */
|
|
136
|
+
async function readDocumentAsync(root, key) {
|
|
137
|
+
const path = join(mediaDirectory(root, key), 'media.json');
|
|
138
|
+
try {
|
|
139
|
+
const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
140
|
+
try {
|
|
141
|
+
if (!(await handle.stat()).isFile())
|
|
142
|
+
throw new Error('Invalid Social Manager media document.');
|
|
143
|
+
const value = JSON.parse(await handle.readFile('utf8'));
|
|
144
|
+
if (!isDocument(value, key))
|
|
145
|
+
throw new Error('Invalid Social Manager media document.');
|
|
146
|
+
return value;
|
|
147
|
+
}
|
|
148
|
+
finally {
|
|
149
|
+
await handle.close();
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
if (isMissingPathError(error))
|
|
154
|
+
return { version: 1, scope: key, media: [] };
|
|
155
|
+
throw error;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/*** Atomically retain all immutable media metadata for one trusted scope. */
|
|
159
|
+
async function saveDocumentAsync(root, key, document) {
|
|
160
|
+
await writeJsonFileAtomic(join(mediaDirectory(root, key), 'media.json'), document);
|
|
161
|
+
}
|
|
162
|
+
/*** Write bytes through a private temporary path so a restart never observes a partial object. */
|
|
163
|
+
async function writeContentAtomicAsync(path, bytes) {
|
|
164
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
165
|
+
await writeFile(temporary, bytes, { mode: 0o600, flag: 'wx' });
|
|
166
|
+
await rename(temporary, path).catch(async (error) => {
|
|
167
|
+
await unlink(temporary).catch(() => undefined);
|
|
168
|
+
throw error;
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
/*** Read only a regular no-follow content object from the private server-owned directory. */
|
|
172
|
+
async function readContentAsync(path) {
|
|
173
|
+
try {
|
|
174
|
+
const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
175
|
+
try {
|
|
176
|
+
if (!(await handle.stat()).isFile())
|
|
177
|
+
throw new Error('Invalid Social Manager media object.');
|
|
178
|
+
return new Uint8Array(await handle.readFile());
|
|
179
|
+
}
|
|
180
|
+
finally {
|
|
181
|
+
await handle.close();
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
if (isMissingPathError(error))
|
|
186
|
+
return undefined;
|
|
187
|
+
throw error;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/*** Require directories to remain private before storing credentials-adjacent media content. */
|
|
191
|
+
async function requirePrivateDirectoryAsync(path, description) {
|
|
192
|
+
const stat = await lstat(path);
|
|
193
|
+
if (!stat.isDirectory() || (stat.mode & 0o077) !== 0)
|
|
194
|
+
throw new Error(`${description} must be private.`);
|
|
195
|
+
}
|
|
196
|
+
/*** Match one opaque identifier without accepting prefix or path traversal variants. */
|
|
197
|
+
function findMedia(document, mediaId) {
|
|
198
|
+
return isMediaId(mediaId) ? document.media.filter((media) => media.mediaId === mediaId) : [];
|
|
199
|
+
}
|
|
200
|
+
/*** Project durable metadata without disclosing scope ownership details. */
|
|
201
|
+
function toMedia(media) {
|
|
202
|
+
const { mediaId, kind, contentType, byteLength, createdAt } = media;
|
|
203
|
+
return { mediaId, kind, contentType, byteLength, createdAt };
|
|
204
|
+
}
|
|
205
|
+
/*** Validate the persisted envelope and every immutable media record before returning it. */
|
|
206
|
+
function isDocument(value, key) {
|
|
207
|
+
return (isRecord(value) &&
|
|
208
|
+
value.version === 1 &&
|
|
209
|
+
value.scope === key &&
|
|
210
|
+
Array.isArray(value.media) &&
|
|
211
|
+
value.media.every((media) => isStoredMedia(media, key)));
|
|
212
|
+
}
|
|
213
|
+
/*** Validate immutable media metadata and bind its identifier to the persisted scope key. */
|
|
214
|
+
function isStoredMedia(value, key) {
|
|
215
|
+
return (isRecord(value) &&
|
|
216
|
+
isMediaId(value.mediaId) &&
|
|
217
|
+
scopeKeyFromMediaId(value.mediaId) === key &&
|
|
218
|
+
isMediaMetadata(value) &&
|
|
219
|
+
typeof value.tenantId === 'string' &&
|
|
220
|
+
typeof value.projectId === 'string' &&
|
|
221
|
+
typeof value.environmentId === 'string' &&
|
|
222
|
+
typeof value.actorId === 'string');
|
|
223
|
+
}
|
|
224
|
+
/*** Validate the immutable provider-neutral portion of one persisted media record. */
|
|
225
|
+
function isMediaMetadata(value) {
|
|
226
|
+
return ((value.kind === 'image' || value.kind === 'video') &&
|
|
227
|
+
typeof value.contentType === 'string' &&
|
|
228
|
+
mediaKind(value.contentType) === value.kind &&
|
|
229
|
+
typeof value.byteLength === 'number' &&
|
|
230
|
+
Number.isSafeInteger(value.byteLength) &&
|
|
231
|
+
value.byteLength > 0 &&
|
|
232
|
+
value.byteLength <= maximumByteLength &&
|
|
233
|
+
typeof value.createdAt === 'string');
|
|
234
|
+
}
|
|
235
|
+
/*** Keep object filenames confined to opaque hashes generated by this adapter. */
|
|
236
|
+
function isMediaId(value) {
|
|
237
|
+
return typeof value === 'string' && /^media-[a-f0-9]{64}-[a-f0-9]{64}$/.test(value);
|
|
238
|
+
}
|
|
239
|
+
/*** Map server-derived scope hashes into the one private media directory tree. */
|
|
240
|
+
function mediaDirectory(root, key) {
|
|
241
|
+
return join(root, key);
|
|
242
|
+
}
|
package/dist/features/trusted-social-manager-host/adapters/createSocialOperationStoresAsync.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { FacebookPagesOperationStore, InstagramProfessionalOperationStore, LinkedinOperationStore, PinterestOperationStore } from '@ankhorage/social';
|
|
2
|
+
export type SocialOperationStores = Readonly<{
|
|
3
|
+
facebookPages: FacebookPagesOperationStore;
|
|
4
|
+
instagramProfessional: InstagramProfessionalOperationStore;
|
|
5
|
+
linkedin: LinkedinOperationStore;
|
|
6
|
+
pinterest: PinterestOperationStore;
|
|
7
|
+
}>;
|
|
8
|
+
/***
|
|
9
|
+
* Create filesystem-backed Social provider operation stores for one trusted local host.
|
|
10
|
+
* The directory is explicitly single-writer: atomic writes and this mutex coordinate one
|
|
11
|
+
* adapter instance, while multiple processes require an external lock.
|
|
12
|
+
*/
|
|
13
|
+
export declare function createSocialOperationStoresAsync(directory: string): Promise<SocialOperationStores>;
|