create-ilorb 0.0.0-stage → 0.3.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,48 @@
1
+ // Every Cloudflare operation goes through this interface. Two implementations:
2
+ // real.ts — wrangler (deploy, migrations, Pages) + Cloudflare REST API (with token) or wrangler login
3
+ // simulated.ts — in-memory account for tests and the demo: records the calls, answers like Cloudflare and
4
+ // knows how to fail the way it does (duplicate name, token without permission, free plan without queue…)
5
+ // Idempotency lives in the STEPS (look up before creating); the provider only answers.
6
+ import { HumanError } from "../errors.js";
7
+ export function cfError(code, vars = {}, detail) {
8
+ return new HumanError(code, vars, detail);
9
+ }
10
+ /**
11
+ * Translates a Cloudflare error response (REST API or wrangler output) to our code.
12
+ * API v4 codes: 10000/9109 = authentication; 10001/7003 = invalid token/resource; 7403/9106 = no permission;
13
+ * 7502 / "already exists" = duplicate name; "workers.dev subdomain" = account without subdomain; "paid plan" = queue.
14
+ */
15
+ export function classifyCfError(text, ctx = {}) {
16
+ const s = text.toLowerCase();
17
+ const v = { name: ctx.resource ?? '', permission: ctx.permission ?? '' };
18
+ if (/not logged in|you are not authenticated|wrangler login|no oauth token/.test(s))
19
+ return cfError('cf_not_logged_in', v, text);
20
+ if (/invalid api token|invalid access token|\b10000\b|\b9109\b|authentication error/.test(s))
21
+ return cfError('cf_token_invalid', v, text);
22
+ if (/\b7403\b|\b9106\b|not authorized|forbidden|missing permission|permission denied|\b10001\b.*permission/.test(s)) {
23
+ return cfError('cf_token_missing_permission', v, text);
24
+ }
25
+ if (/workers\.dev subdomain|register a workers\.dev|no subdomain/.test(s))
26
+ return cfError('cf_workers_subdomain_missing', v, text);
27
+ if (/queues?.*(paid|workers paid|upgrade)|(paid|upgrade).*queues?/.test(s))
28
+ return cfError('cf_queues_require_paid', v, text);
29
+ if (/r2.*(not enabled|enable r2|purchase)|please enable r2/.test(s))
30
+ return cfError('cf_r2_not_enabled', v, text);
31
+ if (/maximum number of databases|database limit|\b7406\b/.test(s))
32
+ return cfError('cf_d1_limit', v, text);
33
+ if (/already exists|\b7502\b|name is already|already taken/.test(s)) {
34
+ return cfError(/pages|project/.test(s) ? 'cf_pages_name_taken' : 'cf_d1_name_taken', v, text);
35
+ }
36
+ if (/enotfound|econnreset|etimedout|fetch failed|network|socket hang up/.test(s))
37
+ return cfError('cf_network', v, text);
38
+ return cfError('cf_unknown', { ...v, detail: text.trim().split('\n').slice(-3).join(' ').slice(0, 300) }, text);
39
+ }
40
+ /** Permissions the token needs (README → "Cloudflare token"). */
41
+ export const TOKEN_PERMISSIONS = [
42
+ 'Account · Workers Scripts · Edit',
43
+ 'Account · D1 · Edit',
44
+ 'Account · Workers R2 Storage · Edit',
45
+ 'Account · Cloudflare Pages · Edit',
46
+ 'Account · Account Settings · Read',
47
+ 'User · User Details · Read',
48
+ ];
@@ -0,0 +1,211 @@
1
+ // REAL Cloudflare: wrangler (deploy, migrations, Pages) + REST API v4 when CLOUDFLARE_API_TOKEN is set.
2
+ // Without a token, uses the wrangler login (`wrangler login`, done by the buyer) and only wrangler commands.
3
+ // ⚠️ Never run against a real account in this version (owner's order): covered by --dry-run and by tests with
4
+ // fake exec/fetch that check the commands and the response handling.
5
+ import { mkdirSync, rmSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ import { shellLine } from "../exec.js";
8
+ import { writeFileAtomic } from "../fsutil.js";
9
+ import { classifyCfError } from "./provider.js";
10
+ const API = 'https://api.cloudflare.com/client/v4';
11
+ /** The commands/calls of each operation — the SAME ones --dry-run prints. */
12
+ export const CF_COMMANDS = {
13
+ auth: (token) => (token ? ['GET /user/tokens/verify', 'GET /accounts'] : ['wrangler whoami --json']),
14
+ subdomain: (token) => (token ? ['GET /accounts/{account}/workers/subdomain'] : ['(sem token: a URL sai do 1º wrangler deploy)']),
15
+ findD1: (name, token) => (token ? [`GET /accounts/{account}/d1/database?name=${name}`] : ['wrangler d1 list --json']),
16
+ createD1: (name, token) => (token ? [`POST /accounts/{account}/d1/database {"name":"${name}"}`] : [`wrangler d1 create ${name}`]),
17
+ migrate: (db) => [`wrangler d1 migrations apply ${db} --remote`],
18
+ findR2: (name, token) => (token ? [`GET /accounts/{account}/r2/buckets?name_contains=${name}`] : ['wrangler r2 bucket list']),
19
+ createR2: (name, token) => (token ? [`POST /accounts/{account}/r2/buckets {"name":"${name}"}`] : [`wrangler r2 bucket create ${name}`]),
20
+ findQueue: (_, token) => (token ? ['GET /accounts/{account}/queues'] : ['wrangler queues list']),
21
+ createQueue: (name, token) => (token ? [`POST /accounts/{account}/queues {"queue_name":"${name}"}`] : [`wrangler queues create ${name}`]),
22
+ deploy: (keys) => [`wrangler deploy --secrets-file .overture/tmp/<worker>.secrets.json (segredos: ${keys.join(', ') || 'nenhum'}; arquivo 0600 apagado em seguida)`],
23
+ findPages: (name, token) => (token ? [`GET /accounts/{account}/pages/projects/${name}`] : ['wrangler pages project list --json']),
24
+ createPages: (name, token) => token ? [`POST /accounts/{account}/pages/projects {"name":"${name}","production_branch":"main"}`] : [`wrangler pages project create ${name} --production-branch main`],
25
+ deployPages: (name, dir) => [`wrangler pages deploy ${dir} --project-name ${name} --branch main --commit-dirty=true`],
26
+ };
27
+ export class RealCloudflare {
28
+ kind = 'real';
29
+ accountId = null;
30
+ f;
31
+ o;
32
+ constructor(o) {
33
+ this.o = o;
34
+ this.f = o.fetch ?? fetch;
35
+ }
36
+ get fetchDeployed() {
37
+ return this.f;
38
+ }
39
+ get token() {
40
+ return this.o.apiToken?.trim() || null;
41
+ }
42
+ async api(method, path, body, ctx = {}) {
43
+ let res;
44
+ try {
45
+ res = await this.f(API + path, {
46
+ method,
47
+ headers: { authorization: `Bearer ${this.token}`, 'content-type': 'application/json' },
48
+ body: body === undefined ? undefined : JSON.stringify(body),
49
+ signal: AbortSignal.timeout(30_000),
50
+ });
51
+ }
52
+ catch (e) {
53
+ throw classifyCfError(`network ${e.message}`, ctx);
54
+ }
55
+ const json = (await res.json().catch(() => null));
56
+ if (res.status === 404 && method === 'GET')
57
+ return { status: 404, result: null };
58
+ if (!res.ok || json?.success === false) {
59
+ const text = (json?.errors ?? []).map((e) => `${e.code} ${e.message}`).join('; ') || `HTTP ${res.status}`;
60
+ throw classifyCfError(res.status === 403 && !/\d{4}/.test(text) ? `7403 ${text}` : text, ctx);
61
+ }
62
+ return { status: res.status, result: json?.result ?? null };
63
+ }
64
+ async wr(args, opts = {}) {
65
+ const env = {};
66
+ if (this.accountId)
67
+ env.CLOUDFLARE_ACCOUNT_ID = this.accountId;
68
+ if (this.token)
69
+ env.CLOUDFLARE_API_TOKEN = this.token;
70
+ const r = await this.o.exec(this.o.wrangler(), args, { cwd: opts.cwd, env });
71
+ if (r.code !== 0)
72
+ throw classifyCfError(`${r.stderr}\n${r.stdout}\n(${shellLine('wrangler', args)})`, { resource: opts.resource });
73
+ return r.stdout;
74
+ }
75
+ acc() {
76
+ if (!this.accountId)
77
+ throw new Error('useAccount() antes');
78
+ return this.accountId;
79
+ }
80
+ async auth() {
81
+ if (this.token) {
82
+ const v = await this.api('GET', '/user/tokens/verify');
83
+ if (v.result?.status !== 'active')
84
+ throw classifyCfError('invalid api token');
85
+ const a = await this.api('GET', '/accounts?per_page=50');
86
+ let email = null;
87
+ try {
88
+ email = (await this.api('GET', '/user')).result?.email ?? null;
89
+ }
90
+ catch { }
91
+ return { via: 'token', email, accounts: (a.result ?? []).map((x) => ({ id: x.id, name: x.name })) };
92
+ }
93
+ const out = await this.wr(['whoami', '--json']);
94
+ const j = JSON.parse(out.slice(out.indexOf('{')));
95
+ if (j.loggedIn === false)
96
+ throw classifyCfError('not logged in');
97
+ return { via: 'wrangler', email: j.email ?? null, accounts: (j.accounts ?? []).map((x) => ({ id: x.id, name: x.name })) };
98
+ }
99
+ useAccount(accountId) {
100
+ this.accountId = accountId;
101
+ }
102
+ async workersSubdomain() {
103
+ if (!this.token)
104
+ return null;
105
+ try {
106
+ const r = await this.api('GET', `/accounts/${this.acc()}/workers/subdomain`);
107
+ return r.result?.subdomain ?? null;
108
+ }
109
+ catch (e) {
110
+ if (e.code === 'cf_workers_subdomain_missing')
111
+ return null;
112
+ throw e;
113
+ }
114
+ }
115
+ async findD1(name) {
116
+ if (this.token) {
117
+ const r = await this.api('GET', `/accounts/${this.acc()}/d1/database?name=${encodeURIComponent(name)}`);
118
+ const hit = (r.result ?? []).find((d) => d.name === name);
119
+ return hit ? { id: hit.uuid, name } : null;
120
+ }
121
+ const list = JSON.parse(await this.wr(['d1', 'list', '--json']));
122
+ const hit = list.find((d) => d.name === name);
123
+ return hit ? { id: hit.uuid, name } : null;
124
+ }
125
+ async createD1(name) {
126
+ if (this.token) {
127
+ const r = await this.api('POST', `/accounts/${this.acc()}/d1/database`, { name }, { resource: name });
128
+ return { id: r.result.uuid, name };
129
+ }
130
+ const out = await this.wr(['d1', 'create', name], { resource: name });
131
+ const id = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i.exec(out)?.[1];
132
+ if (!id)
133
+ throw classifyCfError(`d1 create sem id: ${out}`, { resource: name });
134
+ return { id, name };
135
+ }
136
+ async applyD1Migrations(input) {
137
+ const out = await this.wr(['d1', 'migrations', 'apply', input.database, '--remote'], { cwd: input.cwd, resource: input.database });
138
+ return { applied: (out.match(/\d{4}_[\w-]+\.sql/g) ?? []).length };
139
+ }
140
+ async findR2(name) {
141
+ if (this.token) {
142
+ const r = await this.api('GET', `/accounts/${this.acc()}/r2/buckets?name_contains=${encodeURIComponent(name)}`, undefined, { resource: name });
143
+ return (r.result?.buckets ?? []).some((b) => b.name === name);
144
+ }
145
+ const out = await this.wr(['r2', 'bucket', 'list'], { resource: name });
146
+ return out.split('\n').some((l) => l.trim() === `name: ${name}`);
147
+ }
148
+ async createR2(name) {
149
+ if (this.token)
150
+ await this.api('POST', `/accounts/${this.acc()}/r2/buckets`, { name }, { resource: name });
151
+ else
152
+ await this.wr(['r2', 'bucket', 'create', name], { resource: name });
153
+ }
154
+ async findQueue(name) {
155
+ if (this.token) {
156
+ const r = await this.api('GET', `/accounts/${this.acc()}/queues`, undefined, { resource: name });
157
+ return (r.result ?? []).some((q) => q.queue_name === name);
158
+ }
159
+ return (await this.wr(['queues', 'list'], { resource: name })).includes(name);
160
+ }
161
+ async createQueue(name) {
162
+ if (this.token)
163
+ await this.api('POST', `/accounts/${this.acc()}/queues`, { queue_name: name }, { resource: name });
164
+ else
165
+ await this.wr(['queues', 'create', name], { resource: name });
166
+ }
167
+ async deployWorker(input) {
168
+ const tmpDir = join(this.o.stateDir, 'tmp');
169
+ mkdirSync(tmpDir, { recursive: true });
170
+ const file = join(tmpDir, `${input.name}.secrets.json`);
171
+ const args = ['deploy'];
172
+ if (Object.keys(input.secrets).length) {
173
+ writeFileAtomic(file, JSON.stringify(input.secrets), 0o600);
174
+ args.push('--secrets-file', file);
175
+ }
176
+ try {
177
+ const out = await this.wr(args, { cwd: input.cwd, resource: input.name });
178
+ const url = /(https:\/\/[\w.-]+\.workers\.dev)/.exec(out)?.[1] ?? null;
179
+ return { url };
180
+ }
181
+ finally {
182
+ rmSync(file, { force: true });
183
+ }
184
+ }
185
+ async findPages(name) {
186
+ if (this.token) {
187
+ const r = await this.api('GET', `/accounts/${this.acc()}/pages/projects/${name}`, undefined, { resource: name });
188
+ return r.result ? { subdomain: r.result.subdomain } : null;
189
+ }
190
+ const out = await this.wr(['pages', 'project', 'list', '--json'], { resource: name });
191
+ const list = JSON.parse(out.slice(out.indexOf('[')));
192
+ const hit = list.find((p) => (p['Project Name'] ?? p.name) === name);
193
+ if (!hit)
194
+ return null;
195
+ const domains = String(hit['Project Domains'] ?? hit.subdomain ?? `${name}.pages.dev`);
196
+ return { subdomain: domains.split(',')[0].trim() };
197
+ }
198
+ async createPages(name) {
199
+ if (this.token) {
200
+ const r = await this.api('POST', `/accounts/${this.acc()}/pages/projects`, { name, production_branch: 'main' }, { resource: name });
201
+ return { subdomain: r.result?.subdomain ?? `${name}.pages.dev` };
202
+ }
203
+ await this.wr(['pages', 'project', 'create', name, '--production-branch', 'main'], { resource: name });
204
+ return (await this.findPages(name)) ?? { subdomain: `${name}.pages.dev` };
205
+ }
206
+ async deployPages(input) {
207
+ await this.wr(['pages', 'deploy', input.dir, '--project-name', input.project, '--branch', 'main', '--commit-dirty=true'], { cwd: input.cwd, resource: input.project });
208
+ const p = await this.findPages(input.project);
209
+ return { url: `https://${p?.subdomain ?? `${input.project}.pages.dev`}` };
210
+ }
211
+ }
@@ -0,0 +1,213 @@
1
+ // SIMULATED Cloudflare: an in-memory account that answers like the real one, records every call (so tests
2
+ // can check order and idempotency) and knows how to fail the way Cloudflare does. Also simulates the published Core
3
+ // (/v1/admin/settings and /v1/admin/auth/methods) so the configuration step can run end to end without network.
4
+ import { randomUUID } from 'node:crypto';
5
+ import { existsSync, readdirSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ import { cfError } from "./provider.js";
8
+ export class SimulatedCloudflare {
9
+ kind = 'simulated';
10
+ calls = [];
11
+ d1 = new Map();
12
+ r2 = new Set();
13
+ queues = new Set();
14
+ workers = new Map();
15
+ pages = new Map();
16
+ /** the published Core, simulated: settings + methods, per host */
17
+ cores = new Map();
18
+ account = null;
19
+ failures;
20
+ o;
21
+ constructor(o = {}) {
22
+ this.o = o;
23
+ this.failures = (o.failures ?? []).map((f) => ({ ...f, left: f.times ?? 1 }));
24
+ for (const n of o.existingD1 ?? [])
25
+ this.d1.set(n, { id: randomUUID(), migrations: new Set() });
26
+ for (const n of o.existingPages ?? [])
27
+ this.pages.set(n, { deploys: 0 });
28
+ }
29
+ async hit(op, arg = '') {
30
+ this.calls.push({ op, arg });
31
+ if (this.o.delayMs)
32
+ await new Promise((r) => setTimeout(r, this.o.delayMs));
33
+ const f = this.failures.find((x) => x.op === op && x.left > 0 && (!x.match || arg.includes(x.match)));
34
+ if (f) {
35
+ f.left--;
36
+ throw cfError(f.code, { name: arg, permission: f.vars?.permission ?? '', ...f.vars }, `simulated ${f.code}`);
37
+ }
38
+ }
39
+ needAccount() {
40
+ if (!this.account)
41
+ throw new Error('useAccount() antes');
42
+ }
43
+ get sub() {
44
+ return this.o.subdomain === undefined ? 'comprador' : this.o.subdomain;
45
+ }
46
+ async auth() {
47
+ await this.hit('auth');
48
+ if (this.o.loggedIn === false)
49
+ throw cfError('cf_not_logged_in');
50
+ return { via: this.o.via ?? 'token', email: this.o.email ?? 'dono@exemplo.com', accounts: this.o.accounts ?? [{ id: 'acc_0123456789abcdef', name: 'Conta do comprador' }] };
51
+ }
52
+ useAccount(id) {
53
+ const ok = (this.o.accounts ?? [{ id: 'acc_0123456789abcdef', name: '' }]).some((a) => a.id === id);
54
+ if (!ok)
55
+ throw cfError('cf_account_not_found', { account: id });
56
+ this.account = id;
57
+ }
58
+ async workersSubdomain() {
59
+ await this.hit('workersSubdomain');
60
+ return this.sub;
61
+ }
62
+ async findD1(name) {
63
+ this.needAccount();
64
+ await this.hit('findD1', name);
65
+ const d = this.d1.get(name);
66
+ return d ? { id: d.id, name } : null;
67
+ }
68
+ async createD1(name) {
69
+ this.needAccount();
70
+ await this.hit('createD1', name);
71
+ if (this.d1.has(name))
72
+ throw cfError('cf_d1_name_taken', { name });
73
+ const id = randomUUID();
74
+ this.d1.set(name, { id, migrations: new Set() });
75
+ return { id, name };
76
+ }
77
+ async applyD1Migrations(input) {
78
+ await this.hit('applyD1Migrations', input.database);
79
+ const db = this.d1.get(input.database);
80
+ if (!db)
81
+ throw cfError('cf_unknown', { detail: `Couldn't find a D1 DB with the name or binding '${input.database}'` });
82
+ const dir = join(input.cwd, 'migrations');
83
+ const files = existsSync(dir) ? readdirSync(dir).filter((f) => f.endsWith('.sql')).sort() : [];
84
+ let applied = 0;
85
+ for (const f of files)
86
+ if (!db.migrations.has(f))
87
+ (db.migrations.add(f), applied++);
88
+ return { applied };
89
+ }
90
+ async findR2(name) {
91
+ this.needAccount();
92
+ await this.hit('findR2', name);
93
+ return this.r2.has(name);
94
+ }
95
+ async createR2(name) {
96
+ this.needAccount();
97
+ await this.hit('createR2', name);
98
+ if (this.o.r2Enabled === false)
99
+ throw cfError('cf_r2_not_enabled', { name });
100
+ if (this.r2.has(name))
101
+ throw cfError('cf_unknown', { detail: 'The bucket you tried to create already exists' });
102
+ this.r2.add(name);
103
+ }
104
+ async findQueue(name) {
105
+ await this.hit('findQueue', name);
106
+ return this.queues.has(name);
107
+ }
108
+ async createQueue(name) {
109
+ await this.hit('createQueue', name);
110
+ if ((this.o.plan ?? 'free') === 'free')
111
+ throw cfError('cf_queues_require_paid', { name });
112
+ this.queues.add(name);
113
+ }
114
+ async deployWorker(input) {
115
+ this.needAccount();
116
+ await this.hit('deployWorker', input.name);
117
+ if (this.sub === null)
118
+ throw cfError('cf_workers_subdomain_missing', { name: input.name });
119
+ const w = this.workers.get(input.name) ?? { name: input.name, deploys: 0, secrets: {}, cwd: input.cwd };
120
+ w.deploys++;
121
+ Object.assign(w.secrets, input.secrets); // like --secrets-file: adds, does not erase
122
+ this.workers.set(input.name, w);
123
+ const url = `https://${input.name}.${this.sub}.workers.dev`;
124
+ if (input.cwd.replace(/\\/g, '/').endsWith('overture-core/api/workers') && !this.cores.has(new URL(url).host)) {
125
+ this.cores.set(new URL(url).host, { settings: { appName: 'Overture', theme: {}, products: [], corsOrigins: [], locales: ['pt', 'es', 'en', 'ar'] }, methods: [], puts: [], links: 0 });
126
+ }
127
+ return { url };
128
+ }
129
+ async findPages(name) {
130
+ this.needAccount();
131
+ await this.hit('findPages', name);
132
+ return this.pages.has(name) ? { subdomain: `${name}.pages.dev` } : null;
133
+ }
134
+ async createPages(name) {
135
+ this.needAccount();
136
+ await this.hit('createPages', name);
137
+ if (this.pages.has(name))
138
+ throw cfError('cf_pages_name_taken', { name });
139
+ this.pages.set(name, { deploys: 0 });
140
+ return { subdomain: `${name}.pages.dev` };
141
+ }
142
+ async deployPages(input) {
143
+ await this.hit('deployPages', input.project);
144
+ const p = this.pages.get(input.project);
145
+ if (!p)
146
+ throw cfError('cf_unknown', { detail: `Project not found: ${input.project}` });
147
+ p.deploys++;
148
+ return { url: `https://${input.project}.pages.dev` };
149
+ }
150
+ /** The published Core, in memory: checks the Bearer against the ADMIN_TOKEN that went along in the deploy. */
151
+ fetchDeployed = async (input, init) => {
152
+ const url = new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url);
153
+ await this.hit('fetch', `${init?.method ?? 'GET'} ${url.pathname}`);
154
+ const core = this.cores.get(url.host);
155
+ const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
156
+ const method0 = init?.method ?? 'GET';
157
+ // PRODUCT Worker published: the simulated one only records the request (e.g. the Quiz sample import) and answers 200
158
+ if (!core && [...this.workers.values()].some((w) => url.host.startsWith(`${w.name}.`))) {
159
+ const auth0 = new Headers(init?.headers).get('authorization') ?? '';
160
+ if (!auth0.startsWith('Bearer at_sim_'))
161
+ return json(401, { error: { code: 'unauthorized', message: 'precisa de login' } });
162
+ const body0 = init?.body ? JSON.parse(String(init.body)) : null;
163
+ this.productCalls.push({ host: url.host, method: method0, path: url.pathname, body: body0 });
164
+ return json(200, { imported: typeof body0?.csv === 'string' ? body0.csv.trim().split('\n').length - 1 : 0 });
165
+ }
166
+ if (!core)
167
+ return json(404, { error: { code: 'not_found', message: 'no worker' } });
168
+ // first-access link exchanged for a panel token (public, single use)
169
+ if (url.pathname === '/v1/auth/bootstrap' && method0 === 'POST')
170
+ return json(200, { accessToken: `at_sim_owner_${core.links}`, refreshToken: 'rt_sim', expiresIn: 900 });
171
+ const worker = [...this.workers.values()].find((w) => url.host.startsWith(`${w.name}.`));
172
+ const auth = new Headers(init?.headers).get('authorization');
173
+ if (!worker?.secrets.ADMIN_TOKEN || auth !== `Bearer ${worker.secrets.ADMIN_TOKEN}`)
174
+ return json(401, { error: { code: 'unauthorized', message: 'precisa de login' } });
175
+ const method = init?.method ?? 'GET';
176
+ const body = init?.body ? JSON.parse(String(init.body)) : null;
177
+ if (url.pathname === '/v1/admin/settings') {
178
+ if (method === 'PUT') {
179
+ core.settings = { ...core.settings, ...body };
180
+ core.puts.push('settings');
181
+ }
182
+ return json(200, core.settings);
183
+ }
184
+ if (url.pathname === '/v1/admin/auth/methods') {
185
+ if (method === 'PUT') {
186
+ for (const m of body) {
187
+ const cur = core.methods.find((x) => x.id === m.id);
188
+ const secrets = { ...(cur?.secrets ?? {}), ...Object.fromEntries(Object.keys(m.secrets ?? {}).map((k) => [k, true])) };
189
+ const next = { ...m, secrets };
190
+ if (cur)
191
+ Object.assign(cur, next);
192
+ else
193
+ core.methods.push(next);
194
+ }
195
+ core.puts.push('methods');
196
+ }
197
+ return json(200, { methods: core.methods, warnings: [] });
198
+ }
199
+ if (url.pathname === '/v1/admin/bootstrap-link' && method === 'POST') {
200
+ // first-access link (single use, 15 min): the simulated one only counts it and returns a fake token
201
+ core.links++;
202
+ const token = `bst_simulado${core.links}_${'x'.repeat(32)}`;
203
+ return json(200, { token, email: body?.email, expiresIn: 900, expiresAt: new Date(Date.now() + 900_000).toISOString(), url: body?.panelUrl ? `${body.panelUrl}/?bootstrap=${token}` : null });
204
+ }
205
+ return json(404, { error: { code: 'not_found', message: url.pathname } });
206
+ };
207
+ /** requests to the PRODUCT Workers (fetchDeployed) */
208
+ productCalls = [];
209
+ /** how many times each operation was called (to check "did not duplicate") */
210
+ count(op, arg) {
211
+ return this.calls.filter((c) => c.op === op && (arg === undefined || c.arg === arg)).length;
212
+ }
213
+ }
@@ -0,0 +1,85 @@
1
+ // Configures the published Core Auth through /v1/admin/* with the ADMIN_TOKEN (contract: overture-core/AUTH-API.md) and generates the
2
+ // owner's first-access link (POST /v1/admin/bootstrap-link: single use, 15 min) — without depending on an email provider.
3
+ // Idempotent: reads first and writes only what changed (each PUT becomes an audit line in the panel).
4
+ import { HumanError } from "./errors.js";
5
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
6
+ export async function configureCore(s, f) {
7
+ const call = async (method, path, body) => {
8
+ let res;
9
+ try {
10
+ res = await f(`${s.authUrl}${path}`, {
11
+ method,
12
+ headers: { authorization: `Bearer ${s.adminToken}`, 'content-type': 'application/json' },
13
+ body: body === undefined ? undefined : JSON.stringify(body),
14
+ signal: AbortSignal.timeout(20_000),
15
+ });
16
+ }
17
+ catch (e) {
18
+ throw new HumanError('core_unreachable', { url: s.authUrl }, e.message);
19
+ }
20
+ const text = await res.text();
21
+ if (!res.ok)
22
+ throw new HumanError('core_admin_rejected', { url: s.authUrl, status: res.status, path }, text.slice(0, 300));
23
+ return text ? JSON.parse(text) : null;
24
+ };
25
+ const changed = [];
26
+ // 1. name, theme, product and panel origins (CORS in production)
27
+ const cur = (await call('GET', '/v1/admin/settings'));
28
+ const patch = {};
29
+ if (cur.appName !== s.appName)
30
+ patch.appName = s.appName;
31
+ if (s.locales.length && !same(cur.locales, s.locales))
32
+ patch.locales = s.locales;
33
+ if (!same(cur.theme, s.theme))
34
+ patch.theme = s.theme;
35
+ const products = [...(cur.products ?? []).filter((p) => p.id !== s.product.id), s.product];
36
+ if (!same((cur.products ?? []).find((p) => p.id === s.product.id), s.product))
37
+ patch.products = products;
38
+ const origins = [...new Set([...(cur.corsOrigins ?? []), ...s.corsOrigins])];
39
+ if (!same(cur.corsOrigins ?? [], origins))
40
+ patch.corsOrigins = origins;
41
+ // the new-login email carries the button to the panel's Account screen (settings.notifyNewLogin stays at the Core default: on)
42
+ if (s.accountUrl && cur.accountUrl !== s.accountUrl)
43
+ patch.accountUrl = s.accountUrl;
44
+ // redirect login: the return URLs of this installation's app (the ones the owner already added stay; the Core accepts up to 20)
45
+ const redirects = [...new Set([...(cur.oauthRedirects ?? []), ...(s.oauthRedirects ?? [])])].slice(0, 20);
46
+ if (s.oauthRedirects?.length && !same(cur.oauthRedirects ?? [], redirects))
47
+ patch.oauthRedirects = redirects;
48
+ if (Object.keys(patch).length) {
49
+ await call('PUT', '/v1/admin/settings', patch);
50
+ changed.push(...Object.keys(patch).map((k) => `settings.${k}`));
51
+ }
52
+ // 2. sign-in methods: email with code as the main one (the buyer turns on the others in the panel)
53
+ const { methods } = (await call('GET', '/v1/admin/auth/methods'));
54
+ const email = methods.find((m) => m.id === 'email_code');
55
+ const onlyPrimary = methods.filter((m) => m.enabled && m.primary);
56
+ const needMethod = !email?.enabled || !email.primary || onlyPrimary.length !== 1;
57
+ const needSecrets = !!s.email && !s.emailAlreadySet;
58
+ if (needMethod || needSecrets) {
59
+ const item = { id: 'email_code', enabled: true, position: 0, primary: true };
60
+ if (needSecrets && s.email)
61
+ item.secrets = { resendApiKey: s.email.resendApiKey, from: s.email.from };
62
+ await call('PUT', '/v1/admin/auth/methods', [item]);
63
+ changed.push(needSecrets ? 'methods.email_code(+secrets)' : 'methods.email_code');
64
+ }
65
+ return { changed };
66
+ }
67
+ /** Owner's first-access link (single use, 15 min). The token NEVER goes to the state/log on disk: only to the screen. */
68
+ export async function createBootstrapLink(authUrl, adminToken, panelUrl, email, f) {
69
+ let res;
70
+ try {
71
+ res = await f(`${authUrl}/v1/admin/bootstrap-link`, {
72
+ method: 'POST',
73
+ headers: { authorization: `Bearer ${adminToken}`, 'content-type': 'application/json' },
74
+ body: JSON.stringify({ email, ...(panelUrl ? { panelUrl } : {}) }),
75
+ signal: AbortSignal.timeout(20_000),
76
+ });
77
+ }
78
+ catch (e) {
79
+ throw new HumanError('core_unreachable', { url: authUrl }, e.message);
80
+ }
81
+ const text = await res.text();
82
+ if (!res.ok)
83
+ throw new HumanError('core_admin_rejected', { url: authUrl, status: res.status, path: '/v1/admin/bootstrap-link' }, text.slice(0, 300));
84
+ return JSON.parse(text);
85
+ }
package/dist/engine.js ADDED
@@ -0,0 +1,52 @@
1
+ // The steps engine: each step has an id, a "hash" of what it depends on and the plan (commands) for --dry-run.
2
+ // Done and with the same hash → skip. Failed → writes "failed" and the error says how to continue (--resume).
3
+ import { createHash } from 'node:crypto';
4
+ import { isHuman } from "./errors.js";
5
+ import { t } from "./i18n/index.js";
6
+ import { saveState } from "./state.js";
7
+ export const hashOf = (...parts) => createHash('sha256').update(JSON.stringify(parts)).digest('hex').slice(0, 16);
8
+ export async function runSteps(ctx, steps) {
9
+ let ran = 0;
10
+ let skipped = 0;
11
+ const total = steps.length;
12
+ for (let i = 0; i < steps.length; i++) {
13
+ const s = steps[i];
14
+ const h = s.hash?.(ctx) ?? '';
15
+ const rec = ctx.state.steps[s.id];
16
+ if (!s.always && rec?.status === 'done' && rec.hash === h) {
17
+ ctx.out.skip(i + 1, total, s.title, t('skip.done'));
18
+ skipped++;
19
+ continue;
20
+ }
21
+ ctx.out.step(i + 1, total, s.title);
22
+ const t0 = Date.now();
23
+ try {
24
+ const outputs = (await s.run(ctx)) ?? undefined;
25
+ ctx.state.steps[s.id] = { status: 'done', hash: h, at: new Date().toISOString(), ...(outputs ? { outputs } : {}) };
26
+ saveState(ctx.dir, ctx.state);
27
+ ctx.out.log(` ${t('done.in', { s: ((Date.now() - t0) / 1000).toFixed(1) })}`);
28
+ ran++;
29
+ }
30
+ catch (e) {
31
+ ctx.state.steps[s.id] = { status: 'failed', hash: h, at: new Date().toISOString(), error: { code: isHuman(e) ? e.code : 'unexpected' } };
32
+ saveState(ctx.dir, ctx.state);
33
+ throw e;
34
+ }
35
+ }
36
+ return { ran, skipped };
37
+ }
38
+ export function printPlan(ctx, steps) {
39
+ const total = steps.length;
40
+ ctx.out.line(ctx.out.bold(t('dry.title')));
41
+ ctx.out.line();
42
+ steps.forEach((s, i) => {
43
+ const h = s.hash?.(ctx) ?? '';
44
+ const rec = ctx.state.steps[s.id];
45
+ const done = !s.always && rec?.status === 'done' && rec.hash === h;
46
+ ctx.out.line(`${ctx.out.cyan(`${i + 1}/${total}`)} ${ctx.out.bold(s.title)}${done ? ' ' + ctx.out.dim(t('dry.done')) : ''}`);
47
+ for (const l of s.plan(ctx))
48
+ ctx.out.cmd(l);
49
+ });
50
+ ctx.out.line();
51
+ ctx.out.line(ctx.out.dim(t('dry.end')));
52
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,23 @@
1
+ // "Human" error: each failure has a code, and the code has three texts in the CLI languages —
2
+ // what happened, what to do and (through the installer) how to continue from where it stopped.
3
+ import { t } from "./i18n/index.js";
4
+ export class HumanError extends Error {
5
+ code;
6
+ vars;
7
+ /** technical text (command output, response body) — goes to the log, and a piece of it to the screen */
8
+ detail;
9
+ constructor(code, vars = {}, detail) {
10
+ super(code);
11
+ this.name = 'HumanError';
12
+ this.code = code;
13
+ this.vars = vars;
14
+ this.detail = detail;
15
+ }
16
+ what() {
17
+ return t(`err.${this.code}.what`, this.vars);
18
+ }
19
+ todo() {
20
+ return t(`err.${this.code}.do`, this.vars);
21
+ }
22
+ }
23
+ export const isHuman = (e) => e instanceof HumanError;