@playcraft/build 0.1.89 → 0.1.90

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 (113) hide show
  1. package/dist/audio-source-files.d.ts +5 -0
  2. package/dist/audio-source-files.js +135 -0
  3. package/dist/base-builder.js +41 -2
  4. package/dist/delivery/agent-build-runner.d.ts +44 -0
  5. package/dist/delivery/agent-build-runner.js +365 -0
  6. package/dist/delivery/agent-build-source.d.ts +8 -0
  7. package/dist/delivery/agent-build-source.js +25 -0
  8. package/dist/delivery/artifact-descriptor.d.ts +31 -0
  9. package/dist/delivery/artifact-descriptor.js +237 -0
  10. package/dist/delivery/artifact-package.d.ts +43 -0
  11. package/dist/delivery/artifact-package.js +283 -0
  12. package/dist/delivery/build-plan.d.ts +4 -0
  13. package/dist/delivery/build-plan.js +189 -0
  14. package/dist/delivery/build-plan.types.d.ts +51 -0
  15. package/dist/delivery/build-plan.types.js +1 -0
  16. package/dist/delivery/command-isolation.d.ts +7 -0
  17. package/dist/delivery/command-isolation.js +252 -0
  18. package/dist/delivery/commands.d.ts +5 -0
  19. package/dist/delivery/commands.js +137 -0
  20. package/dist/delivery/files.d.ts +9 -0
  21. package/dist/delivery/files.js +144 -0
  22. package/dist/delivery/git-source-fingerprint.d.ts +2 -0
  23. package/dist/delivery/git-source-fingerprint.js +58 -0
  24. package/dist/delivery/isolated-source.d.ts +5 -0
  25. package/dist/delivery/isolated-source.js +126 -0
  26. package/dist/delivery/output-publication.d.ts +21 -0
  27. package/dist/delivery/output-publication.js +444 -0
  28. package/dist/delivery/project-delivery.d.ts +6 -0
  29. package/dist/delivery/project-delivery.js +287 -0
  30. package/dist/delivery/recipe-build-plan.d.ts +4 -0
  31. package/dist/delivery/recipe-build-plan.js +53 -0
  32. package/dist/delivery/recipe.d.ts +20 -0
  33. package/dist/delivery/recipe.js +211 -0
  34. package/dist/delivery/safe-path.d.ts +2 -0
  35. package/dist/delivery/safe-path.js +18 -0
  36. package/dist/delivery/types.d.ts +76 -0
  37. package/dist/delivery/types.js +1 -0
  38. package/dist/engines/engine-detector.js +4 -0
  39. package/dist/engines/generic-adapter.js +14 -19
  40. package/dist/index.d.ts +19 -4
  41. package/dist/index.js +11 -2
  42. package/dist/platforms/adikteev.js +1 -0
  43. package/dist/platforms/applovin.js +1 -0
  44. package/dist/platforms/base.js +2 -2
  45. package/dist/platforms/bigo.js +1 -0
  46. package/dist/platforms/facebook.js +1 -0
  47. package/dist/platforms/google.js +1 -0
  48. package/dist/platforms/inmobi.js +1 -0
  49. package/dist/platforms/ironsource.js +1 -0
  50. package/dist/platforms/liftoff.js +1 -0
  51. package/dist/platforms/mintegral.js +1 -0
  52. package/dist/platforms/moloco.js +1 -0
  53. package/dist/platforms/playcraft.js +1 -0
  54. package/dist/platforms/remerge.js +1 -0
  55. package/dist/platforms/snapchat.js +1 -0
  56. package/dist/platforms/tiktok.js +1 -0
  57. package/dist/platforms/unity.js +1 -0
  58. package/dist/production-animation-presence.d.ts +2 -0
  59. package/dist/production-animation-presence.js +146 -0
  60. package/dist/production-inputs.d.ts +30 -0
  61. package/dist/production-inputs.js +262 -0
  62. package/dist/production-source-paths.d.ts +5 -0
  63. package/dist/production-source-paths.js +27 -0
  64. package/dist/types.d.ts +5 -0
  65. package/dist/validation/artifact-qa.d.ts +44 -0
  66. package/dist/validation/artifact-qa.js +170 -0
  67. package/dist/validation/artifact-rules.d.ts +28 -0
  68. package/dist/validation/artifact-rules.js +440 -0
  69. package/dist/validation/artifact.d.ts +14 -0
  70. package/dist/validation/artifact.js +188 -0
  71. package/dist/validation/html-validator.d.ts +5 -0
  72. package/dist/validation/html-validator.js +19 -17
  73. package/dist/validation/index.d.ts +4 -0
  74. package/dist/validation/index.js +4 -0
  75. package/dist/validation/package-validator.d.ts +2 -0
  76. package/dist/validation/package-validator.js +25 -64
  77. package/dist/validation/profiles.d.ts +13 -1
  78. package/dist/validation/profiles.js +27 -0
  79. package/dist/validation/runtime-load.d.ts +89 -0
  80. package/dist/validation/runtime-load.js +654 -0
  81. package/dist/validation/source-scanner.d.ts +11 -0
  82. package/dist/validation/source-scanner.js +32 -2
  83. package/dist/validation/types.d.ts +155 -2
  84. package/dist/validation/types.js +1 -1
  85. package/dist/validation/validation-runner.d.ts +22 -2
  86. package/dist/validation/validation-runner.js +68 -3
  87. package/dist/validation/zip-reader.d.ts +7 -0
  88. package/dist/validation/zip-reader.js +159 -26
  89. package/dist/vite/config-builder-generic.d.ts +3 -1
  90. package/dist/vite/config-builder-generic.js +9 -7
  91. package/dist/vite/config-builder.js +1 -1
  92. package/dist/vite/plugin-platform.js +30 -54
  93. package/dist/vite/plugin-source-builder.d.ts +2 -14
  94. package/dist/vite/plugin-source-builder.js +61 -997
  95. package/dist/vite/source-builder-asset-paths.d.ts +25 -0
  96. package/dist/vite/source-builder-asset-paths.js +154 -0
  97. package/dist/vite/source-builder-esm.d.ts +7 -0
  98. package/dist/vite/source-builder-esm.js +877 -0
  99. package/dist/vite/source-builder-types.d.ts +14 -0
  100. package/dist/vite/source-builder-types.js +1 -0
  101. package/dist/vite/workspace.d.ts +6 -0
  102. package/dist/vite/workspace.js +41 -0
  103. package/dist/vite-builder.d.ts +4 -5
  104. package/dist/vite-builder.js +33 -34
  105. package/dist/workspace-css-imports.d.ts +2 -0
  106. package/dist/workspace-css-imports.js +139 -0
  107. package/dist/workspace-model-source.d.ts +14 -0
  108. package/dist/workspace-model-source.js +184 -0
  109. package/dist/workspace-public-imports.d.ts +11 -0
  110. package/dist/workspace-public-imports.js +232 -0
  111. package/dist/workspace-public-source.d.ts +15 -0
  112. package/dist/workspace-public-source.js +564 -0
  113. package/package.json +15 -3
@@ -0,0 +1,189 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { agentBuildSourceRulesVersionSchema } from '@playcraft/common/cloud-workspace/runtime';
3
+ import { CHANNEL_RULE_PROFILES } from '../validation/profiles.js';
4
+ import { ProjectDeliveryError, relativePath } from './recipe.js';
5
+ const HASH = /^[a-f0-9]{64}$/;
6
+ const COMMIT = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
7
+ const FORMATS = ['html', 'zip'];
8
+ const PACKAGE_MANAGERS = ['pnpm', 'npm', 'yarn', 'bun'];
9
+ const COMPILE_STRATEGIES = ['project-command', 'platform-vite', 'project-owned'];
10
+ const PACKAGE_STRATEGIES = ['single-html', 'normalized-zip', 'project-owned'];
11
+ function invalid(message, file) {
12
+ throw new ProjectDeliveryError('delivery_build_plan_invalid', message, file);
13
+ }
14
+ function record(value, field) {
15
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
16
+ invalid(`${field} must be an object`);
17
+ }
18
+ return value;
19
+ }
20
+ function keys(value, allowed, field) {
21
+ const actual = Object.keys(value).sort();
22
+ const expected = [...allowed].sort();
23
+ if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) {
24
+ invalid(`${field} has missing or unsupported fields`);
25
+ }
26
+ }
27
+ function allowedKeys(value, allowed, field) {
28
+ if (Object.keys(value).some((key) => !allowed.includes(key))) {
29
+ invalid(`${field} has unsupported fields`);
30
+ }
31
+ }
32
+ function text(value, field, maximum = 4096) {
33
+ if (typeof value !== 'string' || !value.trim() || value.length > maximum || value.includes('\0')) {
34
+ invalid(`Invalid ${field}`);
35
+ }
36
+ return value;
37
+ }
38
+ function hash(value, field) {
39
+ const result = text(value, field, 64);
40
+ if (!HASH.test(result))
41
+ invalid(`${field} must be a lowercase SHA-256 digest`);
42
+ return result;
43
+ }
44
+ function choice(value, values, field) {
45
+ if (typeof value !== 'string' || !values.includes(value))
46
+ invalid(`Invalid ${field}`);
47
+ return value;
48
+ }
49
+ function command(value, field) {
50
+ const input = record(value, field);
51
+ allowedKeys(input, ['argv', 'cwd', 'timeoutMs'], field);
52
+ if (!Array.isArray(input.argv) || input.argv.length === 0 || input.argv.length > 128) {
53
+ invalid(`${field}.argv must be a nonempty bounded array`);
54
+ }
55
+ const result = {
56
+ argv: input.argv.map((argument, index) => text(argument, `${field}.argv[${index}]`)),
57
+ };
58
+ if (input.cwd !== undefined) {
59
+ result.cwd = relativePath(text(input.cwd, `${field}.cwd`), `${field}.cwd`, true);
60
+ }
61
+ if (input.timeoutMs !== undefined) {
62
+ if (!Number.isInteger(input.timeoutMs) || Number(input.timeoutMs) < 1000 || Number(input.timeoutMs) > 1800000) {
63
+ invalid(`${field}.timeoutMs must be between 1000 and 1800000`);
64
+ }
65
+ result.timeoutMs = Number(input.timeoutMs);
66
+ }
67
+ return result;
68
+ }
69
+ function optionalCommands(value, field) {
70
+ if (!Array.isArray(value) || value.length > 16)
71
+ invalid(`Invalid ${field}`);
72
+ return value.map((item, index) => command(item, `${field}[${index}]`));
73
+ }
74
+ function relativePaths(value, field) {
75
+ if (!Array.isArray(value) || value.length > 32)
76
+ invalid(`Invalid ${field}`);
77
+ const paths = value.map((item, index) => relativePath(text(item, `${field}[${index}]`), `${field}[${index}]`));
78
+ if (new Set(paths).size !== paths.length)
79
+ invalid(`${field} contains duplicates`);
80
+ return paths;
81
+ }
82
+ /** Strictly parses the portable plan; absolute Runtime workspace paths are deliberately absent. */
83
+ export function parseBuildPlan(value) {
84
+ const input = record(value, 'buildPlan');
85
+ keys(input, ['planVersion', 'source', 'target', 'environment', 'setup', 'compile', 'delivery'], 'buildPlan');
86
+ if (input.planVersion !== 1)
87
+ invalid('buildPlan.planVersion must be 1');
88
+ const source = record(input.source, 'source');
89
+ keys(source, ['commitHash', 'sourceFingerprint', 'sourceRulesVersion', 'recipeDigest'], 'source');
90
+ const commitHash = text(source.commitHash, 'source.commitHash', 64);
91
+ if (!COMMIT.test(commitHash))
92
+ invalid('source.commitHash must be a lowercase Git object id');
93
+ const sourceRules = agentBuildSourceRulesVersionSchema.safeParse(source.sourceRulesVersion);
94
+ if (!sourceRules.success)
95
+ invalid('Unsupported source.sourceRulesVersion');
96
+ const target = record(input.target, 'target');
97
+ keys(target, ['channel', 'format'], 'target');
98
+ const channel = text(target.channel, 'target.channel', 64);
99
+ if (!Object.prototype.hasOwnProperty.call(CHANNEL_RULE_PROFILES, channel))
100
+ invalid('Unsupported target.channel');
101
+ const format = choice(target.format, FORMATS, 'target.format');
102
+ const environment = record(input.environment, 'environment');
103
+ keys(environment, ['packageManager', 'executables', 'isolation', 'maxDurationMs'], 'environment');
104
+ if (environment.isolation !== 'managed-delivery-v1')
105
+ invalid('Unsupported environment.isolation');
106
+ if (!Number.isInteger(environment.maxDurationMs) || Number(environment.maxDurationMs) < 1000 || Number(environment.maxDurationMs) > 1800000) {
107
+ invalid('environment.maxDurationMs must be between 1000 and 1800000');
108
+ }
109
+ if (!Array.isArray(environment.executables) || environment.executables.length > 32) {
110
+ invalid('Invalid environment.executables');
111
+ }
112
+ const setup = record(input.setup, 'setup');
113
+ keys(setup, ['install', 'prepareCommands', 'generatedDirectories'], 'setup');
114
+ if (setup.install !== 'frozen-lockfile')
115
+ invalid('setup.install must be frozen-lockfile');
116
+ const compile = record(input.compile, 'compile');
117
+ const output = record(compile.output, 'compile.output');
118
+ keys(output, ['kind', 'directory', 'entry'], 'compile.output');
119
+ const kind = choice(output.kind, ['web-bundle', 'channel-package'], 'compile.output.kind');
120
+ const strategy = choice(compile.strategy, COMPILE_STRATEGIES, 'compile.strategy');
121
+ const scope = choice(compile.scope, ['shared', 'per-channel'], 'compile.scope');
122
+ const hasCommand = compile.command !== undefined;
123
+ keys(compile, hasCommand ? ['strategy', 'command', 'scope', 'output'] : ['strategy', 'scope', 'output'], 'compile');
124
+ if (strategy !== 'project-owned' && !hasCommand) {
125
+ invalid('Project-command and platform-vite strategies require a compile command');
126
+ }
127
+ if (scope === 'shared' && (kind !== 'web-bundle' || strategy === 'project-owned')) {
128
+ invalid('Only a project-compiled web-bundle can be shared across channels');
129
+ }
130
+ const delivery = record(input.delivery, 'delivery');
131
+ keys(delivery, ['channelRulesVersion', 'packageStrategy'], 'delivery');
132
+ const packageStrategy = choice(delivery.packageStrategy, PACKAGE_STRATEGIES, 'delivery.packageStrategy');
133
+ if (kind === 'channel-package' && (strategy === 'platform-vite' || packageStrategy !== 'project-owned')) {
134
+ invalid('A channel-package must stay project-owned and must not enter platform Vite packaging');
135
+ }
136
+ if (kind === 'web-bundle' && packageStrategy === 'project-owned') {
137
+ invalid('A web-bundle requires platform-owned final packaging');
138
+ }
139
+ return {
140
+ planVersion: 1,
141
+ source: {
142
+ commitHash,
143
+ sourceFingerprint: hash(source.sourceFingerprint, 'source.sourceFingerprint'),
144
+ sourceRulesVersion: sourceRules.data,
145
+ recipeDigest: hash(source.recipeDigest, 'source.recipeDigest'),
146
+ },
147
+ target: { channel: channel, format },
148
+ environment: {
149
+ packageManager: choice(environment.packageManager, PACKAGE_MANAGERS, 'environment.packageManager'),
150
+ executables: environment.executables.map((item, index) => text(item, `environment.executables[${index}]`)),
151
+ isolation: 'managed-delivery-v1',
152
+ maxDurationMs: Number(environment.maxDurationMs),
153
+ },
154
+ setup: {
155
+ install: 'frozen-lockfile',
156
+ prepareCommands: optionalCommands(setup.prepareCommands, 'setup.prepareCommands'),
157
+ generatedDirectories: relativePaths(setup.generatedDirectories, 'setup.generatedDirectories'),
158
+ },
159
+ compile: {
160
+ strategy,
161
+ ...(hasCommand ? { command: command(compile.command, 'compile.command') } : {}),
162
+ scope,
163
+ output: {
164
+ kind,
165
+ directory: relativePath(text(output.directory, 'compile.output.directory'), 'compile.output.directory'),
166
+ entry: relativePath(text(output.entry, 'compile.output.entry'), 'compile.output.entry'),
167
+ },
168
+ },
169
+ delivery: {
170
+ channelRulesVersion: text(delivery.channelRulesVersion, 'delivery.channelRulesVersion', 64),
171
+ packageStrategy,
172
+ },
173
+ };
174
+ }
175
+ function canonical(value) {
176
+ if (Array.isArray(value))
177
+ return `[${value.map(canonical).join(',')}]`;
178
+ if (value && typeof value === 'object') {
179
+ const entries = Object.entries(value)
180
+ .filter(([, item]) => item !== undefined)
181
+ .sort(([left], [right]) => left.localeCompare(right));
182
+ return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(',')}}`;
183
+ }
184
+ return JSON.stringify(value) ?? 'null';
185
+ }
186
+ export function buildPlanDigest(value) {
187
+ const plan = parseBuildPlan(value);
188
+ return createHash('sha256').update(`playcraft-build-plan-v1\0${canonical(plan)}`).digest('hex');
189
+ }
@@ -0,0 +1,51 @@
1
+ import type { AgentBuildSourceRulesVersion } from '@playcraft/common/cloud-workspace/runtime';
2
+ import type { OutputFormat, Platform } from '../types.js';
3
+ import type { DeliveryCommand } from './types.js';
4
+ export type BuildPackageManager = 'pnpm' | 'npm' | 'yarn' | 'bun';
5
+ export type BuildPlan = {
6
+ planVersion: 1;
7
+ source: {
8
+ commitHash: string;
9
+ sourceFingerprint: string;
10
+ sourceRulesVersion: AgentBuildSourceRulesVersion;
11
+ recipeDigest: string;
12
+ };
13
+ target: {
14
+ channel: Platform;
15
+ format: OutputFormat;
16
+ };
17
+ environment: {
18
+ packageManager: BuildPackageManager;
19
+ executables: string[];
20
+ isolation: 'managed-delivery-v1';
21
+ maxDurationMs: number;
22
+ };
23
+ setup: {
24
+ install: 'frozen-lockfile';
25
+ prepareCommands: DeliveryCommand[];
26
+ generatedDirectories: string[];
27
+ };
28
+ compile: {
29
+ strategy: 'project-command' | 'platform-vite' | 'project-owned';
30
+ command?: DeliveryCommand;
31
+ scope: 'shared' | 'per-channel';
32
+ output: {
33
+ kind: 'web-bundle' | 'channel-package';
34
+ directory: string;
35
+ entry: string;
36
+ };
37
+ };
38
+ delivery: {
39
+ channelRulesVersion: string;
40
+ packageStrategy: 'single-html' | 'normalized-zip' | 'project-owned';
41
+ };
42
+ };
43
+ export type RecipeBuildPlanOptions = {
44
+ commitHash: string;
45
+ sourceFingerprint: string;
46
+ sourceRulesVersion: AgentBuildSourceRulesVersion;
47
+ channel: Platform;
48
+ format: OutputFormat;
49
+ packageManager: BuildPackageManager;
50
+ maxDurationMs?: number;
51
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,7 @@
1
+ export type DeliveryCommandIsolation = {
2
+ projectRoot: string;
3
+ isolatedRoot: string;
4
+ dependencyRoots?: readonly string[];
5
+ };
6
+ /** Construct argv for the existing managed launcher; never execute or fall back here. */
7
+ export declare function wrapDeliveryCommand(argv: readonly string[], options: DeliveryCommandIsolation): Promise<string[]>;
@@ -0,0 +1,252 @@
1
+ import { constants } from 'node:fs';
2
+ import { access, lstat, realpath, stat } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { ProjectDeliveryError } from './recipe.js';
5
+ const SYSTEM_PATHS = [
6
+ '/bin',
7
+ '/usr/bin',
8
+ '/usr/lib',
9
+ '/usr/lib64',
10
+ '/usr/libexec',
11
+ '/lib',
12
+ '/lib64',
13
+ '/usr/local/bin',
14
+ '/usr/local/lib',
15
+ '/usr/share/nodejs',
16
+ '/etc/ld.so.cache',
17
+ '/etc/localtime',
18
+ '/etc/nsswitch.conf',
19
+ '/etc/passwd',
20
+ '/etc/group',
21
+ '/etc/ssl/openssl.cnf',
22
+ '/etc/crypto-policies/back-ends/opensslcnf.config',
23
+ '/dev/null',
24
+ '/dev/zero',
25
+ '/dev/random',
26
+ '/dev/urandom',
27
+ ];
28
+ const MAC_SYSTEM_PATHS = [
29
+ '/System/Library',
30
+ '/System/Volumes/Preboot/Cryptexes/OS/System/Library',
31
+ '/System/Volumes/Preboot/Cryptexes/OS/usr/lib',
32
+ '/Library/Apple/System/Library',
33
+ '/Library/Developer/CommandLineTools',
34
+ '/Applications/Xcode.app/Contents/Developer',
35
+ '/private/var/db/dyld',
36
+ '/opt/homebrew/bin',
37
+ '/opt/homebrew/lib',
38
+ '/opt/homebrew/opt',
39
+ '/opt/homebrew/Cellar',
40
+ '/opt/homebrew/share',
41
+ '/opt/homebrew/etc/openssl@3/openssl.cnf',
42
+ '/usr/local/Cellar',
43
+ '/usr/local/opt',
44
+ '/usr/local/share',
45
+ '/usr/local/etc/openssl@3/openssl.cnf',
46
+ ];
47
+ function inside(root, candidate) {
48
+ return candidate === root || candidate.startsWith(`${root}${path.sep}`);
49
+ }
50
+ function failure(message) {
51
+ throw new ProjectDeliveryError('delivery_isolation_unavailable', message);
52
+ }
53
+ async function allowedPath(value, optional = false) {
54
+ try {
55
+ const canonical = await realpath(value);
56
+ const info = await stat(canonical, { bigint: true });
57
+ if (!info.isDirectory() && !info.isFile() && !info.isCharacterDevice())
58
+ failure('An isolation allowance has an unsupported file type');
59
+ return {
60
+ path: canonical,
61
+ directory: info.isDirectory(),
62
+ dev: info.dev.toString(),
63
+ ino: info.ino.toString(),
64
+ };
65
+ }
66
+ catch (error) {
67
+ if (optional && error.code === 'ENOENT')
68
+ return undefined;
69
+ if (error instanceof ProjectDeliveryError)
70
+ throw error;
71
+ failure('An isolation allowance could not be verified');
72
+ }
73
+ }
74
+ async function executable(value) {
75
+ try {
76
+ await access(value, constants.X_OK);
77
+ if (!(await stat(value)).isFile())
78
+ failure('The isolation launcher is not a file');
79
+ }
80
+ catch {
81
+ failure('The required operating-system isolation launcher is unavailable');
82
+ }
83
+ }
84
+ // Kernel user API: https://docs.kernel.org/userspace-api/landlock.html .
85
+ // ABI (Application Binary Interface, 应用二进制接口) 3 is required: both
86
+ // cross-directory REFER and TRUNCATE must be handled; there is no fallback.
87
+ // The packed path-beneath structure and syscall numbers come from Linux's
88
+ // include/uapi/linux/landlock.h and x86/asm-generic syscall tables.
89
+ const LANDLOCK_LAUNCHER = String.raw `
90
+ import ctypes, json, os, platform, resource, stat, sys
91
+
92
+ def fail(reason):
93
+ sys.stderr.write("delivery_isolation_unavailable:" + reason + "\n")
94
+ sys.exit(125)
95
+
96
+ try:
97
+ if sys.platform != "linux" or platform.machine() not in ("x86_64", "aarch64", "riscv64"):
98
+ fail("unsupported_landlock_architecture")
99
+ policy = json.loads(sys.argv[1])
100
+ command = sys.argv[2:]
101
+ if not command:
102
+ fail("missing_command")
103
+ # Landlock does not revoke already-open descriptors. Preserve only managed
104
+ # stdio, never an inherited directory/file handle into the original tree.
105
+ ceiling = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
106
+ if ceiling == resource.RLIM_INFINITY:
107
+ ceiling = os.sysconf("SC_OPEN_MAX")
108
+ os.closerange(3, ceiling)
109
+ libc = ctypes.CDLL(None, use_errno=True)
110
+ libc.syscall.restype = ctypes.c_long
111
+ abi = libc.syscall(444, ctypes.c_void_p(), ctypes.c_size_t(0), ctypes.c_uint(1))
112
+ if abi < 3:
113
+ fail("landlock_abi_3_required")
114
+ handled = (1 << 15) - 1
115
+ if abi >= 5:
116
+ handled |= 1 << 15
117
+ if abi >= 9:
118
+ handled |= 1 << 16
119
+ class Ruleset(ctypes.Structure):
120
+ _fields_ = [("handled_access_fs", ctypes.c_uint64)]
121
+ class Beneath(ctypes.Structure):
122
+ _pack_ = 1
123
+ _fields_ = [("allowed_access", ctypes.c_uint64), ("parent_fd", ctypes.c_int32)]
124
+ attr = Ruleset(handled)
125
+ ruleset = libc.syscall(444, ctypes.byref(attr), ctypes.sizeof(attr), 0)
126
+ if ruleset < 0:
127
+ fail("landlock_ruleset_failed")
128
+ read = (1 << 0) | (1 << 2) | (1 << 3)
129
+ write = (1 << 1) | (1 << 4) | (1 << 5) | (1 << 7) | (1 << 8) | (1 << 9) | (1 << 10) | (1 << 12) | (1 << 13) | (1 << 14)
130
+ file_rights = (1 << 0) | (1 << 1) | (1 << 2) | (1 << 14) | (1 << 15)
131
+ for item in policy["read"]:
132
+ if os.path.realpath(item["path"]) != item["path"]:
133
+ fail("allowance_changed")
134
+ fd = os.open(item["path"], os.O_PATH | os.O_CLOEXEC | os.O_NOFOLLOW)
135
+ info = os.fstat(fd)
136
+ if str(info.st_dev) != item["dev"] or str(info.st_ino) != item["ino"]:
137
+ fail("allowance_changed")
138
+ rights = read
139
+ if item["path"] in policy["write"]:
140
+ rights |= write
141
+ if not stat.S_ISDIR(info.st_mode):
142
+ rights &= file_rights
143
+ rule = Beneath(rights & handled, fd)
144
+ result = libc.syscall(445, ruleset, 1, ctypes.byref(rule), 0)
145
+ os.close(fd)
146
+ if result != 0:
147
+ fail("landlock_rule_failed")
148
+ # A fresh, single-threaded launcher applies policy before exec; all future
149
+ # threads/children inherit it. Do not spawn an untracked second executor.
150
+ if libc.prctl(38, 1, 0, 0, 0) != 0:
151
+ fail("no_new_privs_failed")
152
+ if libc.syscall(446, ruleset, 0) != 0:
153
+ fail("landlock_restrict_failed")
154
+ os.close(ruleset)
155
+ os.environ["TMPDIR"] = policy["temporary"]
156
+ os.environ["TMP"] = policy["temporary"]
157
+ os.environ["TEMP"] = policy["temporary"]
158
+ os.execvpe(command[0], command, os.environ)
159
+ except Exception:
160
+ fail("landlock_setup_or_exec_failed")
161
+ `;
162
+ /** Construct argv for the existing managed launcher; never execute or fall back here. */
163
+ export async function wrapDeliveryCommand(argv, options) {
164
+ if (!argv[0] || argv.some((value) => value.includes('\0')))
165
+ failure('The isolated command is invalid');
166
+ if (process.platform !== 'darwin' && process.platform !== 'linux')
167
+ failure('Delivery file isolation is unsupported on this operating system');
168
+ // Loader injection would execute before Python/Seatbelt establishes policy.
169
+ if (['LD_PRELOAD', 'LD_AUDIT', 'DYLD_INSERT_LIBRARIES', 'DYLD_LIBRARY_PATH'].some((key) => process.env[key]))
170
+ failure('Inherited loader injection is incompatible with delivery file isolation');
171
+ const project = await allowedPath(options.projectRoot);
172
+ const isolated = await allowedPath(options.isolatedRoot);
173
+ if (!project?.directory || !isolated?.directory || inside(isolated.path, project.path))
174
+ failure('The snapshot must be a separate directory from its source');
175
+ const dependencies = [];
176
+ for (const candidate of options.dependencyRoots ?? []) {
177
+ if (path.basename(path.resolve(candidate)) !== 'node_modules')
178
+ failure('Only a genuine node_modules directory can be a dependency allowance');
179
+ const info = await lstat(candidate).catch(() => undefined);
180
+ if (!info?.isDirectory() || info.isSymbolicLink())
181
+ failure('Dependency allowances must be real directories');
182
+ const dependency = await allowedPath(candidate);
183
+ if (!dependency?.directory ||
184
+ inside(dependency.path, project.path) ||
185
+ inside(dependency.path, isolated.path) ||
186
+ inside(isolated.path, dependency.path))
187
+ failure('Dependency allowances cannot expose the source or snapshot parent');
188
+ dependencies.push(dependency);
189
+ }
190
+ const roots = new Map();
191
+ for (const value of [isolated, ...dependencies])
192
+ roots.set(value.path, value);
193
+ const node = await allowedPath(process.execPath);
194
+ const nodePrefix = node ? path.dirname(path.dirname(node.path)) : undefined;
195
+ const candidates = [
196
+ ...SYSTEM_PATHS,
197
+ ...(process.platform === 'darwin' ? MAC_SYSTEM_PATHS : []),
198
+ process.execPath,
199
+ // Accommodate a versioned Node installation without admitting its home directory.
200
+ ...(nodePrefix ? [path.join(nodePrefix, 'bin'), path.join(nodePrefix, 'lib')] : []),
201
+ ];
202
+ for (const candidate of candidates) {
203
+ const item = await allowedPath(candidate, true);
204
+ if (!item)
205
+ continue;
206
+ if (inside(item.path, project.path) || inside(project.path, item.path))
207
+ failure('A system toolchain allowance overlaps the original project');
208
+ if (inside(item.path, isolated.path))
209
+ failure('A system toolchain allowance contains the snapshot');
210
+ roots.set(item.path, item);
211
+ }
212
+ const read = [...roots.values()];
213
+ const write = [isolated.path, (await realpath('/dev/null'))];
214
+ if (process.platform === 'darwin') {
215
+ await executable('/usr/bin/sandbox-exec');
216
+ const filter = (item) => `(${item.directory ? 'subpath' : 'literal'} ${JSON.stringify(item.path)})`;
217
+ const readable = read.map(filter).join(' ');
218
+ const profile = [
219
+ '(version 1)',
220
+ '(allow default)',
221
+ // Metadata remains visible, as with Landlock. New dyld/libignition also
222
+ // opens / as a directory anchor; literal / grants no descendant access.
223
+ // Deny actions take precedence over allow actions in Seatbelt, so encode
224
+ // the exceptions in the deny predicate rather than an overriding allow.
225
+ `(deny file-read-data (require-not (require-any (literal "/") ${readable})))`,
226
+ `(deny file-read-xattr (require-not (require-any ${readable})))`,
227
+ `(deny file-write* (require-not (require-any (subpath ${JSON.stringify(isolated.path)}) (literal "/dev/null"))))`,
228
+ ].join('\n');
229
+ // env is itself sandboxed; it only confines tool temporary files to the snapshot.
230
+ return [
231
+ '/usr/bin/sandbox-exec',
232
+ '-p',
233
+ profile,
234
+ '/usr/bin/env',
235
+ `TMPDIR=${isolated.path}`,
236
+ `TMP=${isolated.path}`,
237
+ `TEMP=${isolated.path}`,
238
+ ...argv,
239
+ ];
240
+ }
241
+ // Use the OS interpreter, never a project-controlled PATH shim or PYTHONPATH.
242
+ await executable('/usr/bin/python3');
243
+ return [
244
+ '/usr/bin/python3',
245
+ '-I',
246
+ '-S',
247
+ '-c',
248
+ LANDLOCK_LAUNCHER,
249
+ JSON.stringify({ read, write, temporary: isolated.path }),
250
+ ...argv,
251
+ ];
252
+ }
@@ -0,0 +1,5 @@
1
+ import type { DeliveryCommand, ProjectDeliveryOptions } from './types.js';
2
+ import { wrapDeliveryCommand } from './command-isolation.js';
3
+ export type DeliveryCommandIsolation = Parameters<typeof wrapDeliveryCommand>[1];
4
+ export declare function requireExecutable(root: string, executable: string, cwd: string, options: ProjectDeliveryOptions, isolation?: DeliveryCommandIsolation): Promise<string>;
5
+ export declare function runDeliveryCommand(root: string, command: DeliveryCommand, replace: (value: string) => string, options: ProjectDeliveryOptions, isolation?: DeliveryCommandIsolation): Promise<void>;
@@ -0,0 +1,137 @@
1
+ import { constants } from 'node:fs';
2
+ import { access, stat } from 'node:fs/promises';
3
+ import { spawn } from 'node:child_process';
4
+ import path from 'node:path';
5
+ import { ProjectDeliveryError } from './recipe.js';
6
+ import { safeExistingPath } from './safe-path.js';
7
+ import { wrapDeliveryCommand } from './command-isolation.js';
8
+ function isolationUnavailable(code, output) {
9
+ return code === 125 && output.includes('delivery_isolation_unavailable:') ||
10
+ /sandbox-exec:.*(?:sandbox_(?:init|apply)|Operation not permitted)/i.test(output);
11
+ }
12
+ export async function requireExecutable(root, executable, cwd, options, isolation) {
13
+ if (options.runCommand) {
14
+ const checkArgv = [
15
+ '/bin/sh',
16
+ '-c',
17
+ 'case "$1" in */*) test -f "$1" && test -x "$1" ;; *) command -v "$1" >/dev/null 2>&1 ;; esac',
18
+ 'delivery-toolchain',
19
+ executable,
20
+ ];
21
+ const check = await options.runCommand({
22
+ argv: isolation ? await wrapDeliveryCommand(checkArgv, isolation) : checkArgv,
23
+ cwd,
24
+ timeoutMs: 10000,
25
+ });
26
+ if (isolation && isolationUnavailable(check.code, `${check.stderr ?? ''}${check.stdout ?? ''}`))
27
+ throw new ProjectDeliveryError('delivery_isolation_unavailable', 'The operating system could not enforce delivery file isolation');
28
+ if (check.code !== 0 || check.canceled || check.timedOut)
29
+ throw new ProjectDeliveryError('delivery_toolchain_missing', `Required executable is unavailable: ${executable}`);
30
+ return executable;
31
+ }
32
+ const search = executable.includes('/') || executable.includes('\\')
33
+ ? [path.resolve(cwd, executable)]
34
+ : [
35
+ path.join(cwd, 'node_modules', '.bin', executable),
36
+ path.join(root, 'node_modules', '.bin', executable),
37
+ ...(process.env.PATH ?? '')
38
+ .split(path.delimiter)
39
+ .map((directory) => path.join(directory, executable)),
40
+ ];
41
+ for (const candidate of search) {
42
+ try {
43
+ await access(candidate, process.platform === 'win32' ? constants.F_OK : constants.X_OK);
44
+ if ((await stat(candidate)).isFile())
45
+ return candidate;
46
+ }
47
+ catch {
48
+ /* Check the next PATH entry. */
49
+ }
50
+ }
51
+ throw new ProjectDeliveryError('delivery_toolchain_missing', `Required executable is unavailable: ${executable}`);
52
+ }
53
+ export async function runDeliveryCommand(root, command, replace, options, isolation) {
54
+ if (options.signal?.aborted)
55
+ throw new ProjectDeliveryError('delivery_canceled', 'Delivery preparation was canceled');
56
+ const cwd = await safeExistingPath(root, replace(command.cwd ?? '.'));
57
+ const argv = command.argv.map(replace);
58
+ const executable = await requireExecutable(root, argv[0], cwd, options, isolation);
59
+ const isolatedArgv = isolation
60
+ ? await wrapDeliveryCommand([executable, ...argv.slice(1)], isolation)
61
+ : undefined;
62
+ const timeoutMs = command.timeoutMs ?? 300000;
63
+ if (options.runCommand) {
64
+ const result = await options.runCommand({ argv: isolatedArgv ?? argv, cwd, timeoutMs });
65
+ if (isolation && isolationUnavailable(result.code, `${result.stderr ?? ''}${result.stdout ?? ''}`))
66
+ throw new ProjectDeliveryError('delivery_isolation_unavailable', 'The operating system could not enforce delivery file isolation');
67
+ if (result.canceled || options.signal?.aborted)
68
+ throw new ProjectDeliveryError('delivery_canceled', 'Delivery preparation was canceled');
69
+ if (result.timedOut)
70
+ throw new ProjectDeliveryError('delivery_command_timeout', `Delivery command exceeded ${timeoutMs}ms`);
71
+ if (result.code !== 0)
72
+ throw new ProjectDeliveryError('delivery_command_failed', `Delivery command exited with ${result.code}: ${(result.stderr || result.stdout || '').slice(-4000)}`);
73
+ return;
74
+ }
75
+ await new Promise((resolve, reject) => {
76
+ let tail = '';
77
+ let timedOut = false;
78
+ const child = spawn(isolatedArgv?.[0] ?? executable, isolatedArgv?.slice(1) ?? argv.slice(1), {
79
+ cwd,
80
+ shell: false,
81
+ detached: process.platform !== 'win32',
82
+ env: {
83
+ ...process.env,
84
+ CI: 'true',
85
+ PLAYCRAFT_DELIVERY_EXECUTING: '1',
86
+ PATH: [
87
+ path.join(cwd, 'node_modules', '.bin'),
88
+ path.join(root, 'node_modules', '.bin'),
89
+ process.env.PATH ?? '',
90
+ ].join(path.delimiter),
91
+ },
92
+ stdio: ['ignore', 'pipe', 'pipe'],
93
+ });
94
+ const stop = () => {
95
+ try {
96
+ if (process.platform !== 'win32' && child.pid)
97
+ process.kill(-child.pid, 'SIGTERM');
98
+ else
99
+ child.kill('SIGTERM');
100
+ }
101
+ catch {
102
+ /* The command may already have exited. */
103
+ }
104
+ };
105
+ const timer = setTimeout(() => {
106
+ timedOut = true;
107
+ stop();
108
+ }, timeoutMs);
109
+ options.signal?.addEventListener('abort', stop, { once: true });
110
+ const collect = (chunk) => {
111
+ tail = (tail + chunk.toString()).slice(-4000);
112
+ };
113
+ child.stdout?.on('data', collect);
114
+ child.stderr?.on('data', collect);
115
+ const cleanup = () => {
116
+ clearTimeout(timer);
117
+ options.signal?.removeEventListener('abort', stop);
118
+ };
119
+ child.once('error', (error) => {
120
+ cleanup();
121
+ reject(new ProjectDeliveryError('delivery_command_failed', error.message));
122
+ });
123
+ child.once('close', (code) => {
124
+ cleanup();
125
+ if (options.signal?.aborted)
126
+ reject(new ProjectDeliveryError('delivery_canceled', 'Delivery preparation was canceled'));
127
+ else if (timedOut)
128
+ reject(new ProjectDeliveryError('delivery_command_timeout', `Delivery command exceeded ${timeoutMs}ms`));
129
+ else if (isolation && isolationUnavailable(code, tail))
130
+ reject(new ProjectDeliveryError('delivery_isolation_unavailable', 'The operating system could not enforce delivery file isolation'));
131
+ else if (code !== 0)
132
+ reject(new ProjectDeliveryError('delivery_command_failed', `Delivery command exited with ${code}: ${tail}`));
133
+ else
134
+ resolve();
135
+ });
136
+ });
137
+ }
@@ -0,0 +1,9 @@
1
+ export declare function inside(root: string, target: string): boolean;
2
+ export declare function safeExistingPath(root: string, relative: string): Promise<string>;
3
+ export declare function checkOutputDirectory(root: string, directory: string): Promise<void>;
4
+ /** Hash content and relative names, never mtime or Git HEAD, so receipts survive a clean clone. */
5
+ export declare function deliverySourceFingerprint(root: string, outputDirectory: string, receiptPath?: string, generatedDirectories?: readonly string[]): Promise<string>;
6
+ /** Versioned projects use the same exact source set as save, batch capture and a clean Worker checkout. */
7
+ export declare function deliveryProductionSourceSnapshot(root: string, outputDirectory: string, receiptPath?: string, generatedDirectories?: readonly string[]): Promise<import("../production-inputs.js").ProductionSourceSnapshot | undefined>;
8
+ export declare function outputFingerprint(root: string, directory: string, entry: string): Promise<string>;
9
+ export declare function entryRevision(root: string, directory: string, entry: string): Promise<string | undefined>;