@ankhorage/projects 0.7.3 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +20 -12
  2. package/dist/capabilities/index.d.ts +330 -0
  3. package/dist/capabilities/index.js +194 -0
  4. package/dist/capabilities/socialManagerMediaAnalytics.d.ts +92 -0
  5. package/dist/capabilities/socialManagerMediaAnalytics.js +75 -0
  6. package/dist/features/projects/composition/composeGeneratedRuntimeMaterialization.d.ts +1 -0
  7. package/dist/features/projects/composition/composeGeneratedRuntimeMaterialization.js +13 -5
  8. package/dist/features/projects/composition/createExpoProjectMaterializer.d.ts +4 -6
  9. package/dist/features/projects/composition/createExpoProjectMaterializer.js +29 -36
  10. package/dist/features/projects/composition/createNavigatorMaterializationFiles.d.ts +14 -0
  11. package/dist/features/projects/composition/createNavigatorMaterializationFiles.js +19 -0
  12. package/dist/features/projects/composition/createRootNavigatorGenerationOptions.d.ts +9 -0
  13. package/dist/features/projects/composition/createRootNavigatorGenerationOptions.js +10 -0
  14. package/dist/features/projects/composition/createSocialManagerServerFiles.d.ts +6 -0
  15. package/dist/features/projects/composition/createSocialManagerServerFiles.js +16 -0
  16. package/dist/features/trusted-social-manager-host/adapters/createConnectionFileSystemRepositories.d.ts +16 -0
  17. package/dist/features/trusted-social-manager-host/adapters/createConnectionFileSystemRepositories.js +201 -0
  18. package/dist/features/trusted-social-manager-host/adapters/createConnectionFileSystemStoreAsync.d.ts +25 -0
  19. package/dist/features/trusted-social-manager-host/adapters/createConnectionFileSystemStoreAsync.js +72 -0
  20. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerDraftStoreAsync.d.ts +7 -0
  21. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerDraftStoreAsync.js +160 -0
  22. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerFlowSecurityAsync.d.ts +19 -0
  23. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerFlowSecurityAsync.js +176 -0
  24. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerMediaPreflight.d.ts +4 -0
  25. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerMediaPreflight.js +37 -0
  26. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerMediaStoreAsync.d.ts +7 -0
  27. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerMediaStoreAsync.js +242 -0
  28. package/dist/features/trusted-social-manager-host/adapters/createSocialOperationStoresAsync.d.ts +13 -0
  29. package/dist/features/trusted-social-manager-host/adapters/createSocialOperationStoresAsync.js +244 -0
  30. package/dist/features/trusted-social-manager-host/adapters/projectSocialManagerConnection.d.ts +53 -0
  31. package/dist/features/trusted-social-manager-host/adapters/projectSocialManagerConnection.js +42 -0
  32. package/dist/features/trusted-social-manager-host/application/createSocialManagerPublicationRuntime.d.ts +10 -0
  33. package/dist/features/trusted-social-manager-host/application/createSocialManagerPublicationRuntime.js +240 -0
  34. package/dist/features/trusted-social-manager-host/application/resolveSocialManagerPublication.d.ts +22 -0
  35. package/dist/features/trusted-social-manager-host/application/resolveSocialManagerPublication.js +97 -0
  36. package/dist/features/trusted-social-manager-host/composition/createSocialManagerCapabilityOperations.d.ts +22 -0
  37. package/dist/features/trusted-social-manager-host/composition/createSocialManagerCapabilityOperations.js +224 -0
  38. package/dist/features/trusted-social-manager-host/composition/createSocialManagerConnectionOperations.d.ts +20 -0
  39. package/dist/features/trusted-social-manager-host/composition/createSocialManagerConnectionOperations.js +152 -0
  40. package/dist/features/trusted-social-manager-host/composition/createSocialManagerLocalProviderFixtures.d.ts +22 -0
  41. package/dist/features/trusted-social-manager-host/composition/createSocialManagerLocalProviderFixtures.js +271 -0
  42. package/dist/features/trusted-social-manager-host/composition/createSocialManagerMediaOperations.d.ts +14 -0
  43. package/dist/features/trusted-social-manager-host/composition/createSocialManagerMediaOperations.js +72 -0
  44. package/dist/features/trusted-social-manager-host/composition/createSocialManagerProvider.d.ts +20 -0
  45. package/dist/features/trusted-social-manager-host/composition/createSocialManagerProvider.js +20 -0
  46. package/dist/features/trusted-social-manager-host/composition/createSocialManagerPublicationOperations.d.ts +15 -0
  47. package/dist/features/trusted-social-manager-host/composition/createSocialManagerPublicationOperations.js +185 -0
  48. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerFileSystemPersistenceAsync.d.ts +14 -0
  49. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerFileSystemPersistenceAsync.js +17 -0
  50. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerHost.d.ts +51 -0
  51. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerHost.js +188 -0
  52. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerLocalHostAsync.d.ts +18 -0
  53. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerLocalHostAsync.js +177 -0
  54. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerLocalServerAsync.d.ts +26 -0
  55. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerLocalServerAsync.js +66 -0
  56. package/dist/features/trusted-social-manager-host/domain/publicationConfig.d.ts +18 -0
  57. package/dist/features/trusted-social-manager-host/domain/publicationConfig.js +77 -0
  58. package/dist/features/trusted-social-manager-host/domain/readSocialManagerConnectionRequest.d.ts +54 -0
  59. package/dist/features/trusted-social-manager-host/domain/readSocialManagerConnectionRequest.js +77 -0
  60. package/dist/features/trusted-social-manager-host/domain/readSocialManagerDraftContent.d.ts +3 -0
  61. package/dist/features/trusted-social-manager-host/domain/readSocialManagerDraftContent.js +47 -0
  62. package/dist/features/trusted-social-manager-host/domain/socialManagerConnectionIdentity.d.ts +17 -0
  63. package/dist/features/trusted-social-manager-host/domain/socialManagerConnectionIdentity.js +17 -0
  64. package/dist/features/trusted-zefix-host/composition/createTrustedZefixHost.d.ts +1 -2
  65. package/dist/features/trusted-zefix-host/composition/createTrustedZefixHost.js +3 -59
  66. package/dist/features/trusted-zefix-host/composition/createTrustedZefixWorkerEntry.d.ts +36 -0
  67. package/dist/features/trusted-zefix-host/composition/createTrustedZefixWorkerEntry.js +105 -0
  68. package/dist/features/trusted-zefix-host/composition/createTrustedZefixWorkerHandler.d.ts +35 -0
  69. package/dist/features/trusted-zefix-host/composition/createTrustedZefixWorkerHandler.js +92 -0
  70. package/dist/features/trusted-zefix-host/composition/zefixOperations.d.ts +20 -0
  71. package/dist/features/trusted-zefix-host/composition/zefixOperations.js +57 -0
  72. package/dist/features/worker-materialization/composition/composeWorkerMaterialization.d.ts +13 -0
  73. package/dist/features/worker-materialization/composition/composeWorkerMaterialization.js +90 -0
  74. package/dist/features/worker-materialization/composition/createWorkerMaterializationFile.d.ts +13 -0
  75. package/dist/features/worker-materialization/composition/createWorkerMaterializationFile.js +48 -0
  76. package/dist/features/worker-materialization/constants/worker.d.ts +6 -0
  77. package/dist/features/worker-materialization/constants/worker.js +6 -0
  78. package/dist/index.d.ts +18 -0
  79. package/dist/index.js +16 -0
  80. package/dist/types/socialManager.d.ts +77 -0
  81. package/dist/types/socialManager.js +1 -0
  82. package/dist/types/socialManagerPublication.d.ts +27 -0
  83. package/dist/types/socialManagerPublication.js +1 -0
  84. package/dist/worker/index.d.ts +3 -0
  85. package/dist/worker/index.js +3 -0
  86. package/package.json +511 -9
@@ -0,0 +1,72 @@
1
+ import { constants, lstat, mkdir, open } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { createKeyedAsyncMutex } from '@ankhorage/utility/concurrency';
4
+ import { isMissingPathError, writeJsonFileAtomic } from '@ankhorage/utility/node/fs';
5
+ import { isRecord } from '@ankhorage/utility/object';
6
+ import { createConnectionFileSystemRepositories, } from './createConnectionFileSystemRepositories.js';
7
+ /***
8
+ * Create private single-writer filesystem persistence for Connection's credential-free ports.
9
+ * The directory is assigned to one process and one adapter instance; cross-process writers are
10
+ * deliberately unsupported and require a database adapter with external coordination.
11
+ */
12
+ export async function createConnectionFileSystemStoreAsync(directory) {
13
+ const root = join(directory, 'connection');
14
+ await mkdir(root, { recursive: true, mode: 0o700 });
15
+ const stat = await lstat(root);
16
+ if (!stat.isDirectory() || (stat.mode & 0o077) !== 0) {
17
+ throw new Error('Connection storage directory must be private.');
18
+ }
19
+ const documentPath = join(root, 'state.json');
20
+ const mutateAsync = createMutationAsync(documentPath);
21
+ const repositories = createConnectionFileSystemRepositories({
22
+ documentPath,
23
+ mutateAsync,
24
+ readDocumentAsync,
25
+ });
26
+ return {
27
+ ...repositories,
28
+ listConnectionsAsync: async (scope) => (await readDocumentAsync(documentPath)).connections.filter((connection) => connection.tenantId === scope.tenantId &&
29
+ connection.projectId === scope.projectId &&
30
+ connection.environmentId === scope.environmentId &&
31
+ connection.actorId === scope.actorId),
32
+ };
33
+ }
34
+ /*** Serialize durable mutations within the explicitly supported adapter instance. */
35
+ function createMutationAsync(documentPath) {
36
+ const mutations = createKeyedAsyncMutex();
37
+ return (operation) => mutations.run('connection', async () => {
38
+ const [next, value] = operation(await readDocumentAsync(documentPath));
39
+ await writeJsonFileAtomic(documentPath, next);
40
+ return value;
41
+ });
42
+ }
43
+ /*** Read the sole atomic state document through a no-follow handle and validate it before use. */
44
+ async function readDocumentAsync(path) {
45
+ try {
46
+ const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
47
+ try {
48
+ if (!(await handle.stat()).isFile())
49
+ throw new Error('Connection storage state must be a regular file.');
50
+ const value = JSON.parse(await handle.readFile('utf8'));
51
+ if (!isDocument(value))
52
+ throw new Error('Connection storage document is invalid.');
53
+ return value;
54
+ }
55
+ finally {
56
+ await handle.close();
57
+ }
58
+ }
59
+ catch (error) {
60
+ if (isMissingPathError(error))
61
+ return { version: 1, attempts: [], connections: [], revocations: [] };
62
+ throw error;
63
+ }
64
+ }
65
+ /*** Check the atomic envelope before its records reach the credential-free host ports. */
66
+ function isDocument(value) {
67
+ return (isRecord(value) &&
68
+ value.version === 1 &&
69
+ Array.isArray(value.attempts) &&
70
+ Array.isArray(value.connections) &&
71
+ Array.isArray(value.revocations));
72
+ }
@@ -0,0 +1,7 @@
1
+ import type { SocialManagerDraftStore } from '../../../types/socialManager.js';
2
+ /***
3
+ * Persist immutable draft revisions for one local development host.
4
+ * The configured directory must be private and trusted. Assign it to one writer
5
+ * process and one adapter instance; this is not a distributed database adapter.
6
+ */
7
+ export declare function createSocialManagerDraftStoreAsync(directory: string): Promise<SocialManagerDraftStore>;
@@ -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
+ }
@@ -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>;
@@ -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
+ }
@@ -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;
@@ -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
+ }
@@ -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>;