@ship.zone/runner 0.1.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.
@@ -0,0 +1,253 @@
1
+ import { join } from '@std/path';
2
+ import { ConfigurationError, RunnerError } from './errors.ts';
3
+ import type { IRegisterRunnerRequest } from './interfaces.ts';
4
+ import { runnerProtocolIdentifier } from './interfaces.ts';
5
+ import { canonicalizeJson, createRunnerCapabilitySnapshot } from './protocol-validator.ts';
6
+
7
+ const identifierPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
8
+ const journalName = 'pending-registration.json';
9
+ const maximumJournalBytes = 64 * 1024;
10
+
11
+ export type TRegistrationRequestTemplate = Omit<
12
+ IRegisterRunnerRequest,
13
+ 'registrationRequestId'
14
+ >;
15
+
16
+ const validateRegistrationRequest = (value: unknown): IRegisterRunnerRequest => {
17
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
18
+ throw new RunnerError('Registration journal must contain a JSON object');
19
+ }
20
+ const record = value as Record<string, unknown>;
21
+ const requiredKeys = [
22
+ 'registrationRequestId',
23
+ 'protocol',
24
+ 'runnerVersion',
25
+ 'name',
26
+ 'capabilities',
27
+ ];
28
+ if (
29
+ Object.keys(record).length !== requiredKeys.length ||
30
+ requiredKeys.some((key) => !Object.hasOwn(record, key)) ||
31
+ Object.keys(record).some((key) => !requiredKeys.includes(key))
32
+ ) {
33
+ throw new RunnerError('Registration journal has an invalid shape');
34
+ }
35
+ if (
36
+ typeof record.registrationRequestId !== 'string' ||
37
+ !identifierPattern.test(record.registrationRequestId)
38
+ ) {
39
+ throw new RunnerError('Registration journal contains an invalid registrationRequestId');
40
+ }
41
+ if (record.protocol !== runnerProtocolIdentifier) {
42
+ throw new RunnerError('Registration journal contains an invalid protocol');
43
+ }
44
+ if (
45
+ typeof record.runnerVersion !== 'string' || record.runnerVersion.length < 1 ||
46
+ record.runnerVersion.length > 64
47
+ ) {
48
+ throw new RunnerError('Registration journal contains an invalid runnerVersion');
49
+ }
50
+ if (typeof record.name !== 'string' || record.name.length < 1 || record.name.length > 128) {
51
+ throw new RunnerError('Registration journal contains an invalid name');
52
+ }
53
+ return {
54
+ registrationRequestId: record.registrationRequestId,
55
+ protocol: runnerProtocolIdentifier,
56
+ runnerVersion: record.runnerVersion,
57
+ name: record.name,
58
+ capabilities: createRunnerCapabilitySnapshot(
59
+ record.capabilities as IRegisterRunnerRequest['capabilities'],
60
+ ),
61
+ };
62
+ };
63
+
64
+ const withoutRequestId = (request: IRegisterRunnerRequest): TRegistrationRequestTemplate => ({
65
+ protocol: request.protocol,
66
+ runnerVersion: request.runnerVersion,
67
+ name: request.name,
68
+ capabilities: request.capabilities,
69
+ });
70
+
71
+ const writeAll = async (file: Deno.FsFile, bytes: Uint8Array): Promise<void> => {
72
+ let offset = 0;
73
+ while (offset < bytes.byteLength) {
74
+ const written = await file.write(bytes.subarray(offset));
75
+ if (written <= 0) throw new RunnerError('Registration journal write made no progress');
76
+ offset += written;
77
+ }
78
+ };
79
+
80
+ const isNotFound = (error: unknown): boolean => error instanceof Deno.errors.NotFound;
81
+
82
+ export class RegistrationStateStore {
83
+ readonly path: string;
84
+
85
+ constructor(private readonly stateDirectory: string) {
86
+ this.path = join(stateDirectory, journalName);
87
+ }
88
+
89
+ async loadOrCreate(
90
+ template: TRegistrationRequestTemplate,
91
+ createRequestId: () => string = crypto.randomUUID,
92
+ ): Promise<IRegisterRunnerRequest> {
93
+ const candidate = validateRegistrationRequest({
94
+ registrationRequestId: 'pending-validation',
95
+ ...template,
96
+ });
97
+ const pending = await this.load();
98
+ if (pending) {
99
+ if (
100
+ canonicalizeJson(withoutRequestId(pending)) !==
101
+ canonicalizeJson(withoutRequestId(candidate))
102
+ ) {
103
+ throw new ConfigurationError(
104
+ 'Runner registration configuration changed while a request is pending',
105
+ );
106
+ }
107
+ return pending;
108
+ }
109
+ const request = validateRegistrationRequest({
110
+ ...candidate,
111
+ registrationRequestId: createRequestId(),
112
+ });
113
+ await this.save(request);
114
+ return request;
115
+ }
116
+
117
+ async load(): Promise<IRegisterRunnerRequest | undefined> {
118
+ await this.ensureDirectory();
119
+ let pathStat: Deno.FileInfo;
120
+ try {
121
+ pathStat = await Deno.lstat(this.path);
122
+ } catch (error) {
123
+ if (isNotFound(error)) return undefined;
124
+ throw error;
125
+ }
126
+ this.assertSafeJournalFile(pathStat);
127
+ if (pathStat.size > maximumJournalBytes) {
128
+ throw new RunnerError('Registration journal exceeds its size limit');
129
+ }
130
+ const file = await Deno.open(this.path, { read: true });
131
+ try {
132
+ const openStat = await file.stat();
133
+ this.assertSafeJournalFile(openStat);
134
+ if (
135
+ (pathStat.dev !== null && openStat.dev !== pathStat.dev) ||
136
+ (pathStat.ino !== null && openStat.ino !== pathStat.ino)
137
+ ) {
138
+ throw new RunnerError('Registration journal changed while it was opened');
139
+ }
140
+ const bytes = new Uint8Array(pathStat.size + 1);
141
+ let offset = 0;
142
+ while (offset < bytes.byteLength) {
143
+ const read = await file.read(bytes.subarray(offset));
144
+ if (read === null) break;
145
+ offset += read;
146
+ }
147
+ if (offset !== pathStat.size) {
148
+ throw new RunnerError('Registration journal changed while it was read');
149
+ }
150
+ let parsed: unknown;
151
+ try {
152
+ parsed = JSON.parse(
153
+ new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, offset)),
154
+ );
155
+ } catch (error) {
156
+ throw new RunnerError('Registration journal is not valid UTF-8 JSON', { cause: error });
157
+ }
158
+ return validateRegistrationRequest(parsed);
159
+ } finally {
160
+ file.close();
161
+ }
162
+ }
163
+
164
+ async save(request: IRegisterRunnerRequest): Promise<void> {
165
+ const validated = validateRegistrationRequest(request);
166
+ await this.ensureDirectory();
167
+ try {
168
+ this.assertSafeJournalFile(await Deno.lstat(this.path));
169
+ } catch (error) {
170
+ if (!isNotFound(error)) throw error;
171
+ }
172
+ const temporaryPath = join(
173
+ this.stateDirectory,
174
+ `.${crypto.randomUUID()}.registration-journal.tmp`,
175
+ );
176
+ const bytes = new TextEncoder().encode(`${JSON.stringify(validated)}\n`);
177
+ if (bytes.byteLength > maximumJournalBytes) {
178
+ throw new RunnerError('Registration journal exceeds its size limit');
179
+ }
180
+ let file: Deno.FsFile | undefined;
181
+ try {
182
+ file = await Deno.open(temporaryPath, {
183
+ write: true,
184
+ createNew: true,
185
+ mode: 0o600,
186
+ });
187
+ await writeAll(file, bytes);
188
+ await file.sync();
189
+ file.close();
190
+ file = undefined;
191
+ await Deno.chmod(temporaryPath, 0o600);
192
+ await Deno.rename(temporaryPath, this.path);
193
+ await Deno.chmod(this.path, 0o600);
194
+ await this.syncDirectory();
195
+ } catch (error) {
196
+ file?.close();
197
+ try {
198
+ await Deno.remove(temporaryPath);
199
+ } catch (cleanupError) {
200
+ if (!isNotFound(cleanupError)) {
201
+ throw new AggregateError(
202
+ [error, cleanupError],
203
+ 'Registration journal write cleanup failed',
204
+ );
205
+ }
206
+ }
207
+ throw error;
208
+ }
209
+ }
210
+
211
+ async clear(): Promise<void> {
212
+ await this.ensureDirectory();
213
+ let stat: Deno.FileInfo;
214
+ try {
215
+ stat = await Deno.lstat(this.path);
216
+ } catch (error) {
217
+ if (isNotFound(error)) return;
218
+ throw error;
219
+ }
220
+ this.assertSafeJournalFile(stat);
221
+ await Deno.remove(this.path);
222
+ await this.syncDirectory();
223
+ }
224
+
225
+ private async ensureDirectory(): Promise<void> {
226
+ await Deno.mkdir(this.stateDirectory, { recursive: true, mode: 0o700 });
227
+ const stat = await Deno.lstat(this.stateDirectory);
228
+ if (!stat.isDirectory || stat.isSymlink) {
229
+ throw new RunnerError('Runner state directory must be a real directory');
230
+ }
231
+ if (Deno.build.os !== 'windows' && stat.mode !== null && (stat.mode & 0o077) !== 0) {
232
+ throw new RunnerError('Runner state directory permissions are not private');
233
+ }
234
+ }
235
+
236
+ private assertSafeJournalFile(stat: Deno.FileInfo): void {
237
+ if (!stat.isFile || stat.isSymlink) {
238
+ throw new RunnerError('Registration journal must be a regular file');
239
+ }
240
+ if (Deno.build.os !== 'windows' && stat.mode !== null && (stat.mode & 0o777) !== 0o600) {
241
+ throw new RunnerError('Registration journal permissions must be 0600');
242
+ }
243
+ }
244
+
245
+ private async syncDirectory(): Promise<void> {
246
+ const directory = await Deno.open(this.stateDirectory, { read: true });
247
+ try {
248
+ await directory.sync();
249
+ } finally {
250
+ directory.close();
251
+ }
252
+ }
253
+ }