@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,26 @@
1
+ import type { AppManifest } from '@ankhorage/contracts';
2
+ import type { InternalRestApiDefinition } from '@ankhorage/contracts/data';
3
+ import type { SocialManagerCaller, SocialManagerScope } from '../../../types/socialManager.js';
4
+ export type CreateTrustedSocialManagerLocalServerAsyncInput = Readonly<{
5
+ readonly appId: string;
6
+ readonly dataDirectory: string;
7
+ readonly definition: InternalRestApiDefinition;
8
+ readonly development: Readonly<{
9
+ readonly enabled: true;
10
+ readonly hostname: '127.0.0.1' | '::1';
11
+ readonly token: string;
12
+ }>;
13
+ readonly scope: SocialManagerScope;
14
+ readonly caller: SocialManagerCaller;
15
+ }>;
16
+ export type TrustedSocialManagerLocalServer = Readonly<{
17
+ readonly closeAsync: () => Promise<void>;
18
+ readonly listenAsync: (port: number) => Promise<void>;
19
+ }>;
20
+ /*** Find the manifest-declared internal API that binds one or more Social Manager capabilities. */
21
+ export declare function findTrustedSocialManagerApiDefinition(manifest: AppManifest): InternalRestApiDefinition | undefined;
22
+ /***
23
+ * Compose the explicitly enabled loopback-only Social Manager development server.
24
+ * It shares one durable Flow runtime between authenticated HTTP operations and the worker.
25
+ */
26
+ export declare function createTrustedSocialManagerLocalServerAsync(input: CreateTrustedSocialManagerLocalServerAsyncInput): Promise<TrustedSocialManagerLocalServer>;
@@ -0,0 +1,66 @@
1
+ import { createFastifyApiServer } from '@ankhorage/api-fastify';
2
+ import { createSocialManagerLocalProviderFixtures } from './createSocialManagerLocalProviderFixtures.js';
3
+ import { createTrustedSocialManagerFileSystemPersistenceAsync } from './createTrustedSocialManagerFileSystemPersistenceAsync.js';
4
+ import { createTrustedSocialManagerLocalHostAsync } from './createTrustedSocialManagerLocalHostAsync.js';
5
+ /*** Find the manifest-declared internal API that binds one or more Social Manager capabilities. */
6
+ export function findTrustedSocialManagerApiDefinition(manifest) {
7
+ return Object.values(manifest.infra.apis ?? {}).find((api) => api.origin === 'internal' &&
8
+ Object.values(api.handlers ?? {}).some((handler) => handler.capability.startsWith('projects.social.')));
9
+ }
10
+ /***
11
+ * Compose the explicitly enabled loopback-only Social Manager development server.
12
+ * It shares one durable Flow runtime between authenticated HTTP operations and the worker.
13
+ */
14
+ export async function createTrustedSocialManagerLocalServerAsync(input) {
15
+ assertDevelopmentConfiguration(input);
16
+ const persistence = await createTrustedSocialManagerFileSystemPersistenceAsync(input.dataDirectory);
17
+ const now = () => new Date().toISOString();
18
+ const fixtures = createSocialManagerLocalProviderFixtures({
19
+ operations: persistence.operations,
20
+ now,
21
+ });
22
+ const host = await createTrustedSocialManagerLocalHostAsync({
23
+ input,
24
+ persistence,
25
+ fixtures,
26
+ now,
27
+ });
28
+ const worker = host.startWorkerAsync?.();
29
+ if (!worker)
30
+ throw new Error('Social Manager host did not expose its Flow worker lifecycle.');
31
+ const server = createFastifyApiServer();
32
+ try {
33
+ await host.registerFastifyAsync(server, { prefix: input.definition.basePath });
34
+ }
35
+ catch (error) {
36
+ await worker.stop();
37
+ await server.close();
38
+ throw error;
39
+ }
40
+ return {
41
+ listenAsync: async (port) => {
42
+ if (!Number.isSafeInteger(port) || port < 1 || port > 65_535)
43
+ throw new Error('Social Manager server port is invalid.');
44
+ await server.listen({ host: input.development.hostname, port });
45
+ },
46
+ closeAsync: async () => {
47
+ await worker.stop();
48
+ await server.close();
49
+ },
50
+ };
51
+ }
52
+ /*** Reject production-shaped, non-loopback, or incomplete development configuration before storage is opened. */
53
+ function assertDevelopmentConfiguration(input) {
54
+ if (!isLoopbackHost(input.development.hostname) ||
55
+ !input.development.token.trim() ||
56
+ input.caller.tenantId !== input.scope.tenantId ||
57
+ input.caller.projectId !== input.scope.projectId ||
58
+ input.caller.environmentId !== input.scope.environmentId ||
59
+ !input.caller.actorId.trim()) {
60
+ throw new Error('Social Manager development fixtures require an explicit loopback configuration.');
61
+ }
62
+ }
63
+ /*** Accept only literal loopback listeners so development fixtures cannot become remotely reachable. */
64
+ function isLoopbackHost(hostname) {
65
+ return hostname === '127.0.0.1' || hostname === '::1';
66
+ }
@@ -0,0 +1,18 @@
1
+ import type { FlowNode } from '@ankhorage/contracts/flow';
2
+ import type { SocialTargetRef } from '@ankhorage/social';
3
+ import type { SocialManagerCaller, SocialManagerScope } from '../../../types/socialManager.js';
4
+ export interface PublicationConfig {
5
+ readonly caller: SocialManagerCaller;
6
+ readonly draftId: string;
7
+ readonly revision: number;
8
+ readonly destinationIndex: number;
9
+ readonly runAt: string;
10
+ readonly connectionRevision: string;
11
+ readonly target: SocialTargetRef;
12
+ }
13
+ /*** Reject a cross-scope or incomplete authenticated caller. */
14
+ export declare function assertCallerScope(scope: SocialManagerScope, caller: SocialManagerScope): void;
15
+ /*** Narrow the persisted server-owned graph configuration before using it. */
16
+ export declare function readPublicationConfig(node: FlowNode, scope: SocialManagerScope): PublicationConfig;
17
+ /*** Compare every provider-neutral destination identity component. */
18
+ export declare function sameTarget(left: SocialTargetRef, right: SocialTargetRef): boolean;
@@ -0,0 +1,77 @@
1
+ import { isRecord } from '@ankhorage/utility/object';
2
+ /*** Reject a cross-scope or incomplete authenticated caller. */
3
+ export function assertCallerScope(scope, caller) {
4
+ if (!scope.tenantId ||
5
+ !scope.projectId ||
6
+ !scope.environmentId ||
7
+ caller.tenantId !== scope.tenantId ||
8
+ caller.projectId !== scope.projectId ||
9
+ caller.environmentId !== scope.environmentId)
10
+ throw new Error('Social publication scope mismatch.');
11
+ }
12
+ /*** Narrow the persisted server-owned graph configuration before using it. */
13
+ export function readPublicationConfig(node, scope) {
14
+ const ref = node.config?.publication;
15
+ const value = ref?.kind === 'inline' ? ref.value : undefined;
16
+ if (!isRecord(value) ||
17
+ !isRecord(value.caller) ||
18
+ !isRecord(value.target) ||
19
+ typeof value.draftId !== 'string' ||
20
+ typeof value.revision !== 'number' ||
21
+ typeof value.destinationIndex !== 'number' ||
22
+ typeof value.runAt !== 'string' ||
23
+ typeof value.connectionRevision !== 'string')
24
+ throw new Error('Invalid publication graph configuration.');
25
+ const caller = readCaller(value.caller);
26
+ const target = readTarget(value.target);
27
+ const config = {
28
+ caller,
29
+ target,
30
+ draftId: value.draftId,
31
+ revision: value.revision,
32
+ destinationIndex: value.destinationIndex,
33
+ runAt: value.runAt,
34
+ connectionRevision: value.connectionRevision,
35
+ };
36
+ assertCallerScope(scope, config.caller);
37
+ return config;
38
+ }
39
+ /*** Project the authenticated actor recorded in the server-created graph. */
40
+ function readCaller(value) {
41
+ if (typeof value.actorId !== 'string' ||
42
+ !value.actorId.trim() ||
43
+ typeof value.tenantId !== 'string' ||
44
+ typeof value.projectId !== 'string' ||
45
+ typeof value.environmentId !== 'string')
46
+ throw new Error('Invalid publication caller.');
47
+ return {
48
+ actorId: value.actorId,
49
+ tenantId: value.tenantId,
50
+ projectId: value.projectId,
51
+ environmentId: value.environmentId,
52
+ };
53
+ }
54
+ /*** Project the exact provider-neutral target pinned by the server. */
55
+ function readTarget(value) {
56
+ if (typeof value.provider !== 'string' ||
57
+ typeof value.accountId !== 'string' ||
58
+ typeof value.accountType !== 'string' ||
59
+ typeof value.destinationId !== 'string' ||
60
+ typeof value.destinationType !== 'string')
61
+ throw new Error('Invalid publication target.');
62
+ return {
63
+ provider: value.provider,
64
+ accountId: value.accountId,
65
+ accountType: value.accountType,
66
+ destinationId: value.destinationId,
67
+ destinationType: value.destinationType,
68
+ };
69
+ }
70
+ /*** Compare every provider-neutral destination identity component. */
71
+ export function sameTarget(left, right) {
72
+ return (left.provider === right.provider &&
73
+ left.accountId === right.accountId &&
74
+ left.accountType === right.accountType &&
75
+ left.destinationId === right.destinationId &&
76
+ left.destinationType === right.destinationType);
77
+ }
@@ -0,0 +1,54 @@
1
+ import type { DelegatedAuthorizationProvider, ManagedConnection } from '@ankhorage/connection';
2
+ import type { SocialManagerCaller } from '../../../types/socialManager.js';
3
+ /*** Parse a narrow connection request while always retaining the authenticated caller identity. */
4
+ export declare function readSocialManagerConnectRequest(body: unknown, caller: SocialManagerCaller, connectionId: string): {
5
+ connectionId: string;
6
+ provider: DelegatedAuthorizationProvider;
7
+ requestedScopes: readonly string[];
8
+ actorId: string;
9
+ tenantId: string;
10
+ projectId: string;
11
+ environmentId: string;
12
+ } | undefined;
13
+ /*** Parse the opaque provider callback envelope without interpreting provider-owned payload data. */
14
+ export declare function readSocialManagerConnectionCallback(body: unknown): {
15
+ attemptId: string;
16
+ payload: string;
17
+ } | undefined;
18
+ /*** Parse an authorized target discovery requirement below a trusted durable connection. */
19
+ export declare function readSocialManagerDiscoveryRequirement(query: Readonly<Record<string, string | readonly string[]>>, connection: ManagedConnection): {
20
+ connection: {
21
+ tenantId: string;
22
+ projectId: string;
23
+ environmentId: string;
24
+ actorId: string;
25
+ provider: DelegatedAuthorizationProvider;
26
+ connectionId: string;
27
+ accountId: string;
28
+ };
29
+ operation: string;
30
+ roles: readonly string[];
31
+ scopes: readonly string[];
32
+ } | undefined;
33
+ /*** Read an opaque target identifier that is later resolved below a caller-owned connection. */
34
+ export declare function readSocialManagerTargetId(body: unknown): string | undefined;
35
+ /*** Build the durable identity shared by target discovery and revocation use cases. */
36
+ export declare function socialManagerConnectionReference(connection: ManagedConnection): {
37
+ tenantId: string;
38
+ projectId: string;
39
+ environmentId: string;
40
+ actorId: string;
41
+ provider: DelegatedAuthorizationProvider;
42
+ connectionId: string;
43
+ accountId: string;
44
+ };
45
+ /*** Build a reconnect request from durable connection ownership rather than client supplied state. */
46
+ export declare function socialManagerReconnectInput(connection: ManagedConnection): {
47
+ tenantId: string;
48
+ projectId: string;
49
+ environmentId: string;
50
+ actorId: string;
51
+ connectionId: string;
52
+ provider: DelegatedAuthorizationProvider;
53
+ requestedScopes: readonly string[];
54
+ };
@@ -0,0 +1,77 @@
1
+ import { isRecord } from '@ankhorage/utility/object';
2
+ /*** Parse a narrow connection request while always retaining the authenticated caller identity. */
3
+ export function readSocialManagerConnectRequest(body, caller, connectionId) {
4
+ if (!isRecord(body) || !isProvider(body.provider) || !isStringArray(body.requestedScopes))
5
+ return undefined;
6
+ return {
7
+ ...caller,
8
+ connectionId,
9
+ provider: body.provider,
10
+ requestedScopes: body.requestedScopes,
11
+ };
12
+ }
13
+ /*** Parse the opaque provider callback envelope without interpreting provider-owned payload data. */
14
+ export function readSocialManagerConnectionCallback(body) {
15
+ return isRecord(body) && typeof body.attemptId === 'string' && typeof body.payload === 'string'
16
+ ? { attemptId: body.attemptId, payload: body.payload }
17
+ : undefined;
18
+ }
19
+ /*** Parse an authorized target discovery requirement below a trusted durable connection. */
20
+ export function readSocialManagerDiscoveryRequirement(query, connection) {
21
+ const { operation } = query;
22
+ return typeof operation === 'string' && operation.trim()
23
+ ? {
24
+ connection: socialManagerConnectionReference(connection),
25
+ operation,
26
+ roles: splitQuery(query.roles),
27
+ scopes: splitQuery(query.scopes),
28
+ }
29
+ : undefined;
30
+ }
31
+ /*** Read an opaque target identifier that is later resolved below a caller-owned connection. */
32
+ export function readSocialManagerTargetId(body) {
33
+ return isRecord(body) && typeof body.targetId === 'string' && body.targetId.trim()
34
+ ? body.targetId
35
+ : undefined;
36
+ }
37
+ /*** Build the durable identity shared by target discovery and revocation use cases. */
38
+ export function socialManagerConnectionReference(connection) {
39
+ return {
40
+ tenantId: connection.tenantId,
41
+ projectId: connection.projectId,
42
+ environmentId: connection.environmentId,
43
+ actorId: connection.actorId,
44
+ provider: connection.provider,
45
+ connectionId: connection.connectionId,
46
+ accountId: connection.accountId,
47
+ };
48
+ }
49
+ /*** Build a reconnect request from durable connection ownership rather than client supplied state. */
50
+ export function socialManagerReconnectInput(connection) {
51
+ return {
52
+ tenantId: connection.tenantId,
53
+ projectId: connection.projectId,
54
+ environmentId: connection.environmentId,
55
+ actorId: connection.actorId,
56
+ connectionId: connection.connectionId,
57
+ provider: connection.provider,
58
+ requestedScopes: connection.grantedScopes,
59
+ };
60
+ }
61
+ /*** Admit only the released delegated-authorization providers. */
62
+ function isProvider(value) {
63
+ return (value === 'facebook-login' ||
64
+ value === 'instagram-login' ||
65
+ value === 'linkedin' ||
66
+ value === 'pinterest');
67
+ }
68
+ /*** Reject empty or non-string requested scopes before authorization state is persisted. */
69
+ function isStringArray(value) {
70
+ return (Array.isArray(value) &&
71
+ value.length > 0 &&
72
+ value.every((item) => typeof item === 'string' && item.trim()));
73
+ }
74
+ /*** Split optional comma-separated query values into nonempty canonical requirement entries. */
75
+ function splitQuery(value) {
76
+ return (typeof value === 'string' ? value.split(',') : (value ?? [])).filter((item) => item.trim().length > 0);
77
+ }
@@ -0,0 +1,3 @@
1
+ import type { SocialManagerDraftContent } from '../../../types/socialManager.js';
2
+ /*** Validate and project only the permitted draft fields; selections confer no authorization. */
3
+ export declare function readSocialManagerDraftContent(value: unknown): SocialManagerDraftContent | undefined;
@@ -0,0 +1,47 @@
1
+ import { isRecord } from '@ankhorage/utility/object';
2
+ /*** Validate and project only the permitted draft fields; selections confer no authorization. */
3
+ export function readSocialManagerDraftContent(value) {
4
+ if (!isRecord(value) ||
5
+ typeof value.title !== 'string' ||
6
+ typeof value.text !== 'string' ||
7
+ !isStringList(value.mediaIds) ||
8
+ !Array.isArray(value.destinations) ||
9
+ (value.link !== undefined && typeof value.link !== 'string')) {
10
+ return undefined;
11
+ }
12
+ const destinations = value.destinations.map(readDestination);
13
+ if (!destinations.every((destination) => destination !== undefined))
14
+ return undefined;
15
+ return {
16
+ title: value.title,
17
+ text: value.text,
18
+ mediaIds: value.mediaIds,
19
+ ...(value.link === undefined ? {} : { link: value.link }),
20
+ destinations,
21
+ };
22
+ }
23
+ /*** Read a credential-free destination selection and its channel-specific content. */
24
+ function readDestination(value) {
25
+ if (!isRecord(value) ||
26
+ typeof value.connectionId !== 'string' ||
27
+ !value.connectionId.trim() ||
28
+ typeof value.targetId !== 'string' ||
29
+ !value.targetId.trim() ||
30
+ typeof value.text !== 'string' ||
31
+ !isStringList(value.mediaIds) ||
32
+ (value.link !== undefined && typeof value.link !== 'string')) {
33
+ return undefined;
34
+ }
35
+ return {
36
+ connectionId: value.connectionId,
37
+ targetId: value.targetId,
38
+ text: value.text,
39
+ mediaIds: value.mediaIds,
40
+ ...(value.link === undefined ? {} : { link: value.link }),
41
+ };
42
+ }
43
+ /*** Accept only opaque, non-empty string identifiers in a media selection. */
44
+ function isStringList(value) {
45
+ return (Array.isArray(value) &&
46
+ value.every((item) => typeof item === 'string' && item.trim().length > 0));
47
+ }
@@ -0,0 +1,17 @@
1
+ import type { ManagedConnection } from '@ankhorage/connection';
2
+ import type { SocialManagerCaller } from '../../../types/socialManager.js';
3
+ /*** Compare the authenticated caller with every durable authorization ownership dimension. */
4
+ export declare function isSocialManagerConnectionOwner(value: Pick<ManagedConnection, keyof SocialManagerCaller>, caller: SocialManagerCaller): boolean;
5
+ /*** Construct one exact server-owned revocation operation for a caller-owned target. */
6
+ export declare function socialManagerRevocationOperation(connection: ManagedConnection, targetId: string): {
7
+ targetId: string;
8
+ authorizationId: string;
9
+ effectId: string;
10
+ tenantId: string;
11
+ projectId: string;
12
+ environmentId: string;
13
+ actorId: string;
14
+ provider: import("@ankhorage/connection").DelegatedAuthorizationProvider;
15
+ connectionId: string;
16
+ accountId: string;
17
+ };
@@ -0,0 +1,17 @@
1
+ import { socialManagerConnectionReference } from './readSocialManagerConnectionRequest.js';
2
+ /*** Compare the authenticated caller with every durable authorization ownership dimension. */
3
+ export function isSocialManagerConnectionOwner(value, caller) {
4
+ return (value.tenantId === caller.tenantId &&
5
+ value.projectId === caller.projectId &&
6
+ value.environmentId === caller.environmentId &&
7
+ value.actorId === caller.actorId);
8
+ }
9
+ /*** Construct one exact server-owned revocation operation for a caller-owned target. */
10
+ export function socialManagerRevocationOperation(connection, targetId) {
11
+ return {
12
+ ...socialManagerConnectionReference(connection),
13
+ targetId,
14
+ authorizationId: connection.authorizationId,
15
+ effectId: `social-revocation:${connection.connectionId}:${connection.authorizationId}:${targetId}`,
16
+ };
17
+ }
@@ -3,7 +3,7 @@ import { type FastifyInstance, type RegisterFastifyApiOptions } from '@ankhorage
3
3
  import type { InternalRestApiDefinition } from '@ankhorage/contracts/data';
4
4
  import { type EndpointTestFetch } from '@ankhorage/data-sources';
5
5
  import type { SecretStoreAdapter } from '@ankhorage/secrets/port';
6
- type TrustedZefixOperation = 'company.search' | 'company.get-by-uid';
6
+ import { type TrustedZefixOperation } from './zefixOperations.js';
7
7
  export type CreateTrustedZefixHostInput = Readonly<{
8
8
  appId: string;
9
9
  projectId: string;
@@ -27,4 +27,3 @@ export type TrustedZefixHost = Readonly<{
27
27
  }>;
28
28
  /*** Compose declared Zefix operations into an authenticated, project-scoped trusted host. */
29
29
  export declare function createTrustedZefixHost(input: CreateTrustedZefixHostInput): TrustedZefixHost;
30
- export {};
@@ -1,9 +1,9 @@
1
1
  import {} from '@ankhorage/api';
2
2
  import { registerAuthorizedFastifyApiAsync, } from '@ankhorage/api-fastify';
3
- import { createZefixPublicRestApi, mapZefixCompanyResult, } from '@ankhorage/data-sources';
3
+ import { createZefixPublicRestApi } from '@ankhorage/data-sources';
4
4
  import { createRuntimeApiCapabilityExecutor } from '@ankhorage/runtime/api-capabilities';
5
- import { isRecord } from '@ankhorage/utility/object';
6
5
  import { CAPABILITIES } from '../../../capabilities/index.js';
6
+ import { executeZefixOperationAsync } from './zefixOperations.js';
7
7
  /*** Compose declared Zefix operations into an authenticated, project-scoped trusted host. */
8
8
  export function createTrustedZefixHost(input) {
9
9
  assertHostIdentity(input);
@@ -36,7 +36,7 @@ export function createTrustedZefixHost(input) {
36
36
  owner: capability.owner,
37
37
  scope: context,
38
38
  },
39
- handler: async (request) => executeZefixOperationAsync(executor, operation, request),
39
+ handler: async (request) => executeZefixOperationAsync(executor, operation, operation === 'company.search' ? request.body : { id: request.params.id }),
40
40
  };
41
41
  },
42
42
  };
@@ -84,62 +84,6 @@ function createZefixCredentialResolver(input) {
84
84
  : undefined;
85
85
  };
86
86
  }
87
- /*** Execute only an approved Zefix operation and return the curated company projection. */
88
- async function executeZefixOperationAsync(executor, operation, request) {
89
- const input = operation === 'company.search' ? request.body : { id: request.params.id };
90
- const values = isHostBindingRecord(input) ? input : undefined;
91
- const result = await executor({
92
- capability: `api.zefix.${operation}`,
93
- ...(values === undefined ? {} : { input: values }),
94
- });
95
- if (!result.ok)
96
- return zefixUnavailableResponse();
97
- const companies = curateZefixResult(result.data);
98
- return companies === undefined ? zefixUnavailableResponse() : { body: companies };
99
- }
100
- /*** Strip provider wire payloads before any Zefix result crosses the trusted host boundary. */
101
- function curateZefixResult(value) {
102
- if (!Array.isArray(value))
103
- return undefined;
104
- const mapped = value.map((candidate) => {
105
- const company = asZefixCompany(candidate);
106
- return company ? mapZefixCompanyResult(company) : undefined;
107
- });
108
- return mapped.every((result) => result !== undefined)
109
- ? mapped.map((result) => result.company)
110
- : undefined;
111
- }
112
- /*** Return the one credential-safe failure representation for Vault or provider failures. */
113
- function zefixUnavailableResponse() {
114
- return { status: 502, body: { error: { code: 'zefix_unavailable' } } };
115
- }
116
- /*** Narrow unknown endpoint data to the optional-field Zefix short-company DTO. */
117
- function asZefixCompany(value) {
118
- return isRecord(value) &&
119
- optionalString(value.name) &&
120
- optionalString(value.uid) &&
121
- optionalString(value.chid) &&
122
- optionalString(value.legalSeat)
123
- ? value
124
- : undefined;
125
- }
126
- /*** Accept missing or string wire fields while rejecting non-serializable provider data. */
127
- function optionalString(value) {
128
- return value === undefined || typeof value === 'string';
129
- }
130
- /*** Admit only serializable operation input before passing it to Runtime's binding executor. */
131
- function isHostBindingRecord(value) {
132
- return isRecord(value) && Object.values(value).every(isHostBindingValue);
133
- }
134
- /*** Recursively reject host objects and functions from untrusted request input. */
135
- function isHostBindingValue(value) {
136
- return (value === null ||
137
- typeof value === 'string' ||
138
- typeof value === 'number' ||
139
- typeof value === 'boolean' ||
140
- (Array.isArray(value) && value.every(isHostBindingValue)) ||
141
- (isRecord(value) && Object.values(value).every(isHostBindingValue)));
142
- }
143
87
  /*** Resolve the one Projects-owned capability permitted for each declared Zefix operation. */
144
88
  function resolveCapability(operation) {
145
89
  const id = operation === 'company.search'
@@ -0,0 +1,36 @@
1
+ import type { PersistentExternalRequestBudgetPort } from '@ankhorage/api';
2
+ import type { TrustedZefixOperation } from './zefixOperations.js';
3
+ /*** Worker bindings; every value is resolved server-side and never reaches the client bundle. */
4
+ export type TrustedZefixWorkerEnvironment = Readonly<Record<string, string | undefined>>;
5
+ /*** Provider-neutral caller verification port, structurally compatible with `@ankhorage/auth`. */
6
+ export interface TrustedZefixWorkerCallerAuthentication {
7
+ authenticateCaller(input: Readonly<{
8
+ credential?: string;
9
+ }>): Promise<Readonly<{
10
+ status: string;
11
+ caller?: Readonly<{
12
+ id: string;
13
+ }>;
14
+ }>>;
15
+ }
16
+ /*** Durable request budget with its explicit schema and connection lifecycle. */
17
+ export interface TrustedZefixWorkerRequestBudget extends PersistentExternalRequestBudgetPort {
18
+ ensureSchemaAsync(): Promise<void>;
19
+ close(): Promise<void>;
20
+ }
21
+ export type CreateTrustedZefixWorkerEntryInput = Readonly<{
22
+ appId: string;
23
+ projectId: string;
24
+ environment: string;
25
+ operations: Readonly<Record<string, TrustedZefixOperation>>;
26
+ /** Build the caller verifier from the Worker bindings, for example with Neon Auth. */
27
+ createCallerAuthentication: (env: TrustedZefixWorkerEnvironment) => TrustedZefixWorkerCallerAuthentication;
28
+ /** Build the durable budget from the Worker bindings, for example on Neon PostgreSQL. */
29
+ createRequestBudget: (env: TrustedZefixWorkerEnvironment) => TrustedZefixWorkerRequestBudget;
30
+ }>;
31
+ /*** A Cloudflare Worker module whose fetch handler resolves every binding server-side. */
32
+ export interface TrustedZefixWorkerEntry {
33
+ fetch(request: Request, env: TrustedZefixWorkerEnvironment): Promise<Response>;
34
+ }
35
+ /*** Compose the deployable Worker entry from injected adapters and server-side bindings. */
36
+ export declare function createTrustedZefixWorkerEntry(input: CreateTrustedZefixWorkerEntryInput): TrustedZefixWorkerEntry;
@@ -0,0 +1,105 @@
1
+ import { createTrustedZefixWorkerHandler, } from './createTrustedZefixWorkerHandler.js';
2
+ /** Acquisition authorizes exactly two configured subjects; any other configuration denies access. */
3
+ const REQUIRED_SUBJECT_COUNT = 2;
4
+ /*** Compose the deployable Worker entry from injected adapters and server-side bindings. */
5
+ export function createTrustedZefixWorkerEntry(input) {
6
+ // The budget table is created at most once per isolate; a failure is retried, never skipped.
7
+ const schema = { ready: false };
8
+ return {
9
+ fetch: async (request, env) => {
10
+ const budget = createBudget(input, env);
11
+ if (budget === undefined)
12
+ return unavailable();
13
+ try {
14
+ if (!schema.ready) {
15
+ await budget.ensureSchemaAsync();
16
+ schema.ready = true;
17
+ }
18
+ return await createRequestHandler(input, env, budget)(request);
19
+ }
20
+ catch {
21
+ return unavailable();
22
+ }
23
+ finally {
24
+ await budget.close().catch(() => undefined);
25
+ }
26
+ },
27
+ };
28
+ }
29
+ /*** Create the budget, treating any construction failure as an unavailable host. */
30
+ function createBudget(input, env) {
31
+ try {
32
+ return input.createRequestBudget(env);
33
+ }
34
+ catch {
35
+ return undefined;
36
+ }
37
+ }
38
+ /*** Bind the shared trusted handler to this request's verified, allow-listed caller and secrets. */
39
+ function createRequestHandler(input, env, requestBudget) {
40
+ const authentication = input.createCallerAuthentication(env);
41
+ const allowedSubjects = parseAllowedSubjects(env.ANKH_AUTH_ALLOWED_SUBJECTS);
42
+ return createTrustedZefixWorkerHandler({
43
+ appId: input.appId,
44
+ projectId: input.projectId,
45
+ environment: input.environment,
46
+ operations: input.operations,
47
+ requestBudget,
48
+ authenticateCallerAsync: async (request) => {
49
+ const result = await authentication.authenticateCaller(withCredential(readBearerCredential(request)));
50
+ return result.status === 'authenticated' ? result.caller : undefined;
51
+ },
52
+ // Deny every caller unless the server-side allow-list names their verified subject.
53
+ authorizeCallerAsync: ({ caller }) => Promise.resolve(isCallerWithId(caller) && allowedSubjects.has(caller.id)),
54
+ resolveCredentialsAsync: () => Promise.resolve(parseCredentials(env.ZEFIX_CREDENTIALS)),
55
+ });
56
+ }
57
+ /*** Read the bearer credential from the Authorization header only. */
58
+ function readBearerCredential(request) {
59
+ const match = /^Bearer\s+(\S+)$/iu.exec(request.headers.get('authorization')?.trim() ?? '');
60
+ return match?.[1];
61
+ }
62
+ /*** Keep the optional credential property absent rather than undefined. */
63
+ function withCredential(credential) {
64
+ return credential === undefined ? {} : { credential };
65
+ }
66
+ /*** Parse the server-side subject allow-list: exactly two distinct subject IDs, otherwise nobody is allowed. */
67
+ function parseAllowedSubjects(value) {
68
+ const subjects = (value ?? '')
69
+ .split(/[\s,]+/u)
70
+ .map((subject) => subject.trim())
71
+ .filter((subject) => subject.length > 0);
72
+ const distinct = new Set(subjects);
73
+ return subjects.length === REQUIRED_SUBJECT_COUNT && distinct.size === REQUIRED_SUBJECT_COUNT
74
+ ? distinct
75
+ : new Set();
76
+ }
77
+ /*** Parse the server-side Zefix Basic credentials; malformed values count as unavailable. */
78
+ function parseCredentials(value) {
79
+ try {
80
+ const parsed = JSON.parse(value ?? '');
81
+ return isCredentialRecord(parsed) ? parsed : undefined;
82
+ }
83
+ catch {
84
+ return undefined;
85
+ }
86
+ }
87
+ /*** Narrow parsed JSON to non-empty Basic credentials. */
88
+ function isCredentialRecord(value) {
89
+ return (typeof value === 'object' &&
90
+ value !== null &&
91
+ 'username' in value &&
92
+ 'password' in value &&
93
+ typeof value.username === 'string' &&
94
+ typeof value.password === 'string' &&
95
+ value.username.length > 0 &&
96
+ value.password.length > 0);
97
+ }
98
+ /*** Narrow the verified caller to an identity-bearing record. */
99
+ function isCallerWithId(caller) {
100
+ return (typeof caller === 'object' && caller !== null && 'id' in caller && typeof caller.id === 'string');
101
+ }
102
+ /*** Return the one caller-safe response for any host failure. */
103
+ function unavailable() {
104
+ return Response.json({ error: { code: 'external_request_unavailable' } }, { status: 503, headers: { 'cache-control': 'no-store' } });
105
+ }