@ductape/cli 0.5.0 → 0.5.3

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.
@@ -1,7 +1,10 @@
1
1
  import fs from 'node:fs';
2
- export const CLOUD_PROVIDERS = ['aws', 'gcp', 'azure', 'mongodb_atlas', 'neo4j_aura'];
2
+ export const CLOUD_PROVIDERS = ['aws', 'gcp', 'azure', 'cloudflare', 'mongodb_atlas', 'neo4j_aura'];
3
3
  export const realIo = { readFile: (file) => fs.readFileSync(file, 'utf8'), env: process.env };
4
4
  const ROLE_ARN = /^arn:aws[a-z-]*:iam::\d{12}:role\/[\w+=,.@/-]+$/;
5
+ const AZURE_RESOURCE_GROUP = /^[A-Za-z0-9_.()-]{1,89}$/;
6
+ const AZURE_REGISTRY = /^[a-zA-Z0-9]{5,50}$/;
7
+ const AZURE_IDENTITY = /^\/subscriptions\/[0-9a-f-]{36}\/resourceGroups\/[A-Za-z0-9_.()-]+\/providers\/Microsoft\.ManagedIdentity\/userAssignedIdentities\/[A-Za-z0-9_-]+$/i;
5
8
  const RUNTIME_ACCOUNT = /^[A-Za-z0-9._-]+@[A-Za-z0-9.-]+\.iam\.gserviceaccount\.com$|^\d+-compute@developer\.gserviceaccount\.com$/;
6
9
  /** A secret is only ever read from a file or an environment variable, so it never lands in shell history or a process list. */
7
10
  function secretFromEnv(variable, flag, io) {
@@ -37,6 +40,93 @@ function readServiceAccount(file, io) {
37
40
  throw new Error(`${file} is a "${String(parsed.type)}" credential, but a service account key is needed`);
38
41
  return parsed;
39
42
  }
43
+ /** The stack output that fills each connection field, so a person copies nothing by hand. */
44
+ const FARGATE_OUTPUT_FIELDS = {
45
+ ClusterName: 'fargate_cluster', ListenerArn: 'fargate_listener_arn', BaseDomain: 'fargate_base_domain', VpcId: 'fargate_vpc_id', SubnetIds: 'fargate_subnets',
46
+ SecurityGroupId: 'fargate_security_groups', TaskRoleArn: 'fargate_task_role_arn', ExecutionRoleArn: 'fargate_execution_role_arn', LogGroup: 'fargate_log_group',
47
+ };
48
+ /**
49
+ * The Fargate fields of a connection: from the saved outputs of the setup stack, then any individual flag on top. Accepts what
50
+ * `aws cloudformation describe-stacks --stack-name ductape-fargate` prints, the bare list of outputs, or a plain object of them.
51
+ */
52
+ export function fargateFields(flags, io) {
53
+ const out = {};
54
+ if (flags.fargateOutputsFile !== undefined) {
55
+ let parsed;
56
+ try {
57
+ parsed = JSON.parse(io.readFile(flags.fargateOutputsFile));
58
+ }
59
+ catch (error) {
60
+ throw new Error(`Cannot read the stack outputs in ${flags.fargateOutputsFile}: ${error instanceof Error ? error.message : String(error)}. Save them with: aws cloudformation describe-stacks --stack-name ductape-fargate > outputs.json`);
61
+ }
62
+ const root = parsed;
63
+ const list = Array.isArray(root) ? root : Array.isArray(root.Stacks) ? root.Stacks[0]?.Outputs : undefined;
64
+ const values = Array.isArray(list)
65
+ ? Object.fromEntries(list.filter((o) => o?.OutputKey).map((o) => [o.OutputKey, o.OutputValue]))
66
+ : root;
67
+ const missing = Object.keys(FARGATE_OUTPUT_FIELDS).filter((key) => values[key] === undefined || values[key] === '');
68
+ if (missing.length === Object.keys(FARGATE_OUTPUT_FIELDS).length)
69
+ throw new Error(`${flags.fargateOutputsFile} has none of the ductape-fargate stack's outputs (${Object.keys(FARGATE_OUTPUT_FIELDS).join(', ')}). Is it from the right stack?`);
70
+ if (missing.length > 0)
71
+ throw new Error(`${flags.fargateOutputsFile} is missing the stack outputs: ${missing.join(', ')}`);
72
+ for (const [key, field] of Object.entries(FARGATE_OUTPUT_FIELDS))
73
+ out[field] = values[key];
74
+ // Only a stack made with an internal load balancer has a relay function, and having one means the load balancer is internal.
75
+ if (typeof values.VerifierFunctionName === 'string' && values.VerifierFunctionName !== '') {
76
+ out.fargate_verifier_function = values.VerifierFunctionName;
77
+ out.fargate_internal = true;
78
+ }
79
+ }
80
+ const set = (field, value) => { if (value !== undefined)
81
+ out[field] = value; };
82
+ set('fargate_cluster', flags.fargateCluster);
83
+ set('fargate_listener_arn', flags.fargateListenerArn);
84
+ set('fargate_base_domain', flags.fargateBaseDomain);
85
+ set('fargate_vpc_id', flags.fargateVpcId);
86
+ set('fargate_subnets', flags.fargateSubnets);
87
+ set('fargate_security_groups', flags.fargateSecurityGroups);
88
+ set('fargate_task_role_arn', flags.fargateTaskRoleArn);
89
+ set('fargate_execution_role_arn', flags.fargateExecutionRoleArn);
90
+ set('fargate_log_group', flags.fargateLogGroup);
91
+ if (flags.fargatePrivateTasks)
92
+ out.fargate_assign_public_ip = false;
93
+ if (flags.fargateScaleDownIdle !== undefined) {
94
+ if (!['on', 'off'].includes(flags.fargateScaleDownIdle))
95
+ throw new Error('--fargate-scale-down-idle must be on or off');
96
+ out.fargate_scale_down_idle = flags.fargateScaleDownIdle === 'on';
97
+ }
98
+ if (flags.fargateInternal !== undefined) {
99
+ if (!['on', 'off'].includes(flags.fargateInternal))
100
+ throw new Error('--fargate-internal must be on or off');
101
+ out.fargate_internal = flags.fargateInternal === 'on';
102
+ }
103
+ set('fargate_verifier_function', flags.fargateVerifierFunction);
104
+ // ECS Express Mode: one role, from the third stack's saved outputs or given directly.
105
+ if (flags.expressOutputsFile !== undefined) {
106
+ let parsed;
107
+ try {
108
+ parsed = JSON.parse(io.readFile(flags.expressOutputsFile));
109
+ }
110
+ catch (error) {
111
+ throw new Error(`Cannot read the stack outputs in ${flags.expressOutputsFile}: ${error instanceof Error ? error.message : String(error)}. Save them with: aws cloudformation describe-stacks --stack-name ductape-ecs-express > express.json`);
112
+ }
113
+ const root = parsed;
114
+ const list = Array.isArray(root) ? root : Array.isArray(root.Stacks) ? root.Stacks[0]?.Outputs : undefined;
115
+ const found = Array.isArray(list) ? list.find((o) => o?.OutputKey === 'InfrastructureRoleArn')?.OutputValue : root.InfrastructureRoleArn;
116
+ if (typeof found !== 'string' || !found)
117
+ throw new Error(`${flags.expressOutputsFile} has no InfrastructureRoleArn output. Is it from the ductape-ecs-express stack?`);
118
+ out.express_infrastructure_role_arn = found;
119
+ }
120
+ if (flags.expressInfrastructureRoleArn !== undefined)
121
+ out.express_infrastructure_role_arn = flags.expressInfrastructureRoleArn;
122
+ if (out.express_infrastructure_role_arn !== undefined && !ROLE_ARN.test(String(out.express_infrastructure_role_arn)))
123
+ throw new Error('--express-infrastructure-role-arn must look like arn:aws:iam::123456789012:role/DuctapeExpressInfrastructure');
124
+ for (const [field, flag] of [['fargate_task_role_arn', '--fargate-task-role-arn'], ['fargate_execution_role_arn', '--fargate-execution-role-arn']]) {
125
+ if (out[field] !== undefined && !ROLE_ARN.test(String(out[field])))
126
+ throw new Error(`${flag} must look like arn:aws:iam::123456789012:role/DuctapeFargateTask`);
127
+ }
128
+ return out;
129
+ }
40
130
  const compact = (value) => Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined));
41
131
  /**
42
132
  * Builds the request body for `ductape cloud connections <verb>` from flags, on top of any body read from a file. Flags win.
@@ -73,8 +163,8 @@ export function buildConnectionBody(verb, flags, base = {}, io = realIo) {
73
163
  if (flags.scopes !== undefined)
74
164
  scopes = flags.scopes.split(',').map((s) => s.trim()).filter(Boolean);
75
165
  if (flags.deploy) {
76
- if (body.provider !== 'gcp')
77
- throw new Error('--deploy is only available for GCP connections today; AWS and Azure deploy adapters are not built yet');
166
+ if (body.provider !== 'gcp' && body.provider !== 'aws' && body.provider !== 'azure' && body.provider !== 'cloudflare')
167
+ throw new Error('--deploy is only available for GCP, AWS, Azure and Cloudflare connections');
78
168
  scopes = [...new Set([...(scopes ?? []), 'deploy'])];
79
169
  }
80
170
  if (scopes !== undefined) {
@@ -105,6 +195,23 @@ export function buildConnectionBody(verb, flags, base = {}, io = realIo) {
105
195
  throw new Error('--role-arn must look like arn:aws:iam::123456789012:role/ductape-access');
106
196
  body.role_arn = flags.roleArn;
107
197
  }
198
+ // The roles Ductape Deploy hands to the functions it creates and to the builds it starts.
199
+ if (flags.runtimeRoleArn !== undefined) {
200
+ if (!ROLE_ARN.test(flags.runtimeRoleArn))
201
+ throw new Error('--runtime-role-arn must look like arn:aws:iam::123456789012:role/DuctapeFunctionRuntime');
202
+ body.runtime_role_arn = flags.runtimeRoleArn;
203
+ }
204
+ if (flags.buildRoleArn !== undefined) {
205
+ if (!ROLE_ARN.test(flags.buildRoleArn))
206
+ throw new Error('--build-role-arn must look like arn:aws:iam::123456789012:role/DuctapeBuild');
207
+ body.build_role_arn = flags.buildRoleArn;
208
+ }
209
+ if (flags.defaultRegion !== undefined) {
210
+ if (!/^[a-z]{2}(-[a-z]+)+-[0-9]$/.test(flags.defaultRegion))
211
+ throw new Error('--default-region must look like eu-west-2');
212
+ body.default_region = flags.defaultRegion;
213
+ }
214
+ Object.assign(body, fargateFields(flags, io));
108
215
  if (flags.tenantId !== undefined)
109
216
  body.tenant_id = flags.tenantId;
110
217
  if (flags.subscriptionId !== undefined)
@@ -113,9 +220,48 @@ export function buildConnectionBody(verb, flags, base = {}, io = realIo) {
113
220
  body.client_id = flags.clientId;
114
221
  if (flags.defaultLocation !== undefined)
115
222
  body.default_location = flags.defaultLocation;
223
+ // Where Ductape Deploy works on Azure: the outputs of the setup template.
224
+ if (flags.resourceGroup !== undefined) {
225
+ if (!AZURE_RESOURCE_GROUP.test(flags.resourceGroup))
226
+ throw new Error('--resource-group must be a resource group name such as ductape-deploy');
227
+ body.resource_group = flags.resourceGroup;
228
+ }
229
+ if (flags.registryName !== undefined) {
230
+ if (!AZURE_REGISTRY.test(flags.registryName))
231
+ throw new Error('--registry-name must be the container registry name from the setup template: 5 to 50 letters and digits');
232
+ body.registry_name = flags.registryName;
233
+ }
234
+ if (flags.runtimeIdentityId !== undefined) {
235
+ if (!AZURE_IDENTITY.test(flags.runtimeIdentityId))
236
+ throw new Error('--runtime-identity-id must be the full resource id of the user assigned identity, the runtimeIdentityId output of the setup template');
237
+ body.runtime_identity_id = flags.runtimeIdentityId;
238
+ }
239
+ if (flags.keyVaultUri !== undefined) {
240
+ if (flags.keyVaultUri !== '' && !/^https:\/\/[a-z0-9][a-z0-9-]{1,22}[a-z0-9]\.vault\.(azure\.net|azure\.cn|usgovcloudapi\.net|microsoftazure\.de)\/?$/.test(flags.keyVaultUri))
241
+ throw new Error('--key-vault-uri must be a vault address such as https://my-vault.vault.azure.net (an empty value clears it)');
242
+ body.key_vault_uri = flags.keyVaultUri;
243
+ }
244
+ if (flags.environmentName !== undefined) {
245
+ if (!/^[a-z0-9][a-z0-9-]{0,30}[a-z0-9]$/.test(flags.environmentName))
246
+ throw new Error('--environment-name must be the container apps environment name, lowercase letters, digits and hyphens');
247
+ body.environment_name = flags.environmentName;
248
+ }
249
+ if (flags.secretsStoreId !== undefined) {
250
+ if (flags.secretsStoreId !== '' && !/^[a-fA-F0-9]{32}$/.test(flags.secretsStoreId))
251
+ throw new Error('--secrets-store-id must be the 32-character id of the Secrets Store (an empty value clears it)');
252
+ body.secrets_store_id = flags.secretsStoreId.toLowerCase();
253
+ }
116
254
  const azureSecret = secretFromEnv(flags.clientSecretEnv, '--client-secret-env', io);
117
255
  if (azureSecret !== undefined)
118
256
  body.client_secret = azureSecret;
257
+ if (flags.accountId !== undefined) {
258
+ if (!/^[a-fA-F0-9]{32}$/.test(flags.accountId))
259
+ throw new Error('--account-id must be the 32-character Cloudflare account id shown in the dashboard');
260
+ body.account_id = flags.accountId.toLowerCase();
261
+ }
262
+ const cloudflareToken = secretFromEnv(flags.apiTokenEnv, '--api-token-env', io);
263
+ if (cloudflareToken !== undefined)
264
+ body.api_token = cloudflareToken;
119
265
  if (flags.atlasPublicKey !== undefined)
120
266
  body.atlas_public_key = flags.atlasPublicKey;
121
267
  const atlasSecret = secretFromEnv(flags.atlasPrivateKeyEnv, '--atlas-private-key-env', io);
@@ -171,6 +317,163 @@ export const GCP_DEPLOY_TROUBLESHOOTING = [
171
317
  { problem: 'The connection says it was not created for deploys', fix: 'Create it with --deploy so it carries the deploy scope. A connection made for resources only cannot build or deploy.' },
172
318
  { problem: 'A deployed service answers 401 or 403 when you open it in a browser', fix: 'That is intended. Services are private; Ductape calls them with an identity token. Making one public is a separate, approved step that does not exist yet.' },
173
319
  ];
320
+ export const AWS_DEPLOY_ROLE_LIST = [
321
+ { role: 'DuctapeAccess', for: 'the role Ductape assumes; it can only touch Lambda functions named ductape-*, ECR repositories under ductape/, secrets under ductape/, the staging bucket and the build project' },
322
+ { role: 'DuctapeFunctionRuntime', for: 'the role your deployed functions run as: logs, and reading their own secrets under ductape/' },
323
+ { role: 'DuctapeBuild', for: 'the role your builds run as: reading the uploaded source, pushing images and writing logs' },
324
+ ];
325
+ export const AWS_DEPLOY_CREATES = [
326
+ 'An S3 bucket named ductape-source-<ACCOUNT_ID>-<REGION>, where your source is uploaded to be built (private, with public access blocked)',
327
+ 'One ECR repository per function or service, named ductape/<product>-<name>, holding the built images',
328
+ 'A CodeBuild project named ductape-build, and one build per build',
329
+ 'One Lambda function per deployed version of a function or service, with a published version for each release and two aliases: cand (a release being checked) and live (what is serving)',
330
+ 'One function URL per alias, with IAM authentication, so nobody can call a function without AWS credentials',
331
+ 'One Secrets Manager secret per deployed function, under ductape/, holding its signing key (a service gets none)',
332
+ ];
333
+ export const AWS_DEPLOY_SAFETY = 'Ductape only adds resources it tags as its own (ductape_managed), never changes or reuses one it did not create, and never deletes anything, including what it created. Removing deployed resources is always your own action. Use a dedicated account if you can, so what Ductape adds is easy to see.';
334
+ export const AWS_DEPLOY_TROUBLESHOOTING = [
335
+ { problem: 'Validation lists missing permissions', fix: 'The DuctapeAccess role is missing statements of the DuctapeDeploy policy. Re-run the CloudFormation stack from the latest template, or add the statements named in the message, then validate again. IAM changes can take a minute to apply.' },
336
+ { problem: '"The role defined for the function cannot be assumed by Lambda"', fix: 'Check that DuctapeFunctionRuntime trusts lambda.amazonaws.com. A role created moments ago can take a minute or two to be usable; Ductape waits for that, but a wrong trust policy will not fix itself.' },
337
+ { problem: '403 Forbidden when Ductape checks a new release', fix: 'The role needs both lambda:InvokeFunctionUrl and lambda:InvokeFunction. They are in the template; add them if you wrote the policy by hand, and wait a minute.' },
338
+ { problem: '"is not authorized to perform: iam:PassRole"', fix: 'DuctapeAccess may hand only DuctapeFunctionRuntime to Lambda and only DuctapeBuild to CodeBuild. Complete the connection with exactly those role ARNs.' },
339
+ { problem: '"Cannot have more than 1 builds in queue" or builds wait a long time', fix: 'New AWS accounts can run one CodeBuild build at a time. Wait for the running build, or ask for an increase in Service Quotas.' },
340
+ { problem: 'MemorySize or concurrency is rejected', fix: 'New AWS accounts have lower Lambda limits until they build up usage. Ask for an increase in Service Quotas, or lower runtime.memory.' },
341
+ { problem: 'A function is Failed with ImageAccessDenied or InvalidImage', fix: 'Do not add expiry rules to the ECR repositories under ductape/, and do not push images there yourself. Ductape builds images without attestations so Lambda can run them; an image pushed another way may be an index Lambda cannot use.' },
342
+ { problem: 'A function that was not called for weeks fails on its first call', fix: 'Lambda puts container functions that are idle for weeks to sleep and refuses the first call while it wakes. Call again; deploying a new release always wakes it.' },
343
+ { problem: 'The function URL answers 403 in a browser', fix: 'That is intended. Function URLs use IAM authentication; Ductape calls them with signed requests.' },
344
+ ];
345
+ /**
346
+ * Extra steps for a connection that also deploys to AWS Fargate. Lambda needs none of this; Fargate runs your containers behind a load balancer
347
+ * in your account, so it needs a cluster, a certificate for a domain you own, and the permissions to manage them.
348
+ */
349
+ export const AWS_FARGATE_OPTIONAL = {
350
+ title: 'Also deploy to AWS Fargate (optional)',
351
+ summary: 'Runs each release as its own ECS service behind your Application Load Balancer, with weighted traffic between releases. Nothing in this section is needed for Lambda.',
352
+ steps: [
353
+ { step: 1, who: 'you', title: 'Have a domain and a certificate', notes: ['Pick a domain every deployment will be a name under, such as deploy.example.com. In AWS Certificate Manager, request a certificate for the wildcard *.deploy.example.com in the same region and validate it. Ductape sends signed requests only over HTTPS, so there is no plain HTTP option.'] },
354
+ { step: 2, who: 'ductape', title: 'Get the Fargate stack', commands: ['ductape cloud connections get <TAG> --save-fargate-template ductape-fargate.yaml'], notes: ['Available until the connection is active. It is a second stack, run after ductape-deploy.'] },
355
+ {
356
+ step: 3, who: 'you', title: 'Create the cluster, load balancer and roles',
357
+ commands: ['aws cloudformation deploy --stack-name ductape-fargate --template-file ductape-fargate.yaml --capabilities CAPABILITY_NAMED_IAM --region <REGION> --parameter-overrides VpcId=<VPC_ID> SubnetIds=<SUBNET_A>,<SUBNET_B> CertificateArn=<ACM_CERTIFICATE_ARN> BaseDomain=<deploy.example.com>'],
358
+ notes: ['It creates an ECS cluster named ductape, an internet-facing Application Load Balancer with an HTTPS listener that answers 404 until Ductape adds a rule, two security groups (tasks accept traffic from the load balancer only), the task and execution roles, a log group, and attaches the extra permissions to DuctapeAccess. Read it before you run it.'],
359
+ },
360
+ { step: 4, who: 'you', title: 'Point the domain at the load balancer', notes: ['Create a wildcard DNS record, *.deploy.example.com, pointing at the LoadBalancerDnsName output of the stack (a CNAME, or an alias record in Route 53). Every deployment then answers on <name>.deploy.example.com, and a candidate release on <name>--cand.deploy.example.com.'] },
361
+ {
362
+ step: 5, who: 'you', title: 'Optional: limit who can reach the load balancer',
363
+ commands: [
364
+ 'aws ec2 create-managed-prefix-list --prefix-list-name ductape-allowed --address-family IPv4 --max-entries 20 --entries Cidr=<DUCTAPE_ADDRESS>/32,Description=ductape Cidr=<YOUR_CALLERS>/24,Description=callers --region <REGION>',
365
+ 'aws cloudformation deploy --stack-name ductape-fargate --template-file ductape-fargate.yaml --capabilities CAPABILITY_NAMED_IAM --region <REGION> --parameter-overrides <the same parameters as before> AllowedPrefixListId=<PREFIX_LIST_ID>',
366
+ ],
367
+ notes: [
368
+ 'By default anyone can reach the load balancer on 443, and a function is protected by its signature check alone. With a prefix list, only the addresses in it can. It must include the addresses Ductape calls your deployments from (shown as deploy_setup.fargate.controlPlaneAddresses in the connection response; ask your Ductape operator if it is empty), because Ductape checks every release over the network before it takes traffic. If they are missing, releases fail their check as unreachable.',
369
+ 'For a load balancer that is not on the internet at all, add Scheme=internal. Ductape cannot reach it, so the stack also creates a small relay function inside your VPC that makes each check from within; it calls only HTTPS hosts under your domain, holds no key, and is shown as the VerifierFunctionName output. Your domain must then resolve to the internal load balancer from inside the VPC (a private hosted zone).',
370
+ ],
371
+ },
372
+ {
373
+ step: 6, who: 'ductape', title: 'Complete the connection with the stack outputs',
374
+ commands: ['aws cloudformation describe-stacks --stack-name ductape-fargate --region <REGION> > outputs.json', 'ductape cloud connections complete <TAG> --fargate-outputs-file outputs.json'],
375
+ notes: ['Or give each value with --fargate-cluster, --fargate-listener-arn, --fargate-base-domain, --fargate-vpc-id, --fargate-subnets, --fargate-security-groups, --fargate-task-role-arn, --fargate-execution-role-arn and --fargate-log-group. Add --fargate-private-tasks if the subnets are private and reach the internet through a NAT gateway.'],
376
+ },
377
+ { step: 7, who: 'ductape', title: 'Validate it', commands: ['ductape cloud connections validate <TAG>'], notes: ['Also checks that the cluster exists, the listener is HTTPS, the two roles trust ECS, and every extra permission is held.'] },
378
+ ],
379
+ creates: [
380
+ 'One ECS service per release, named <deployment>-<first 12 characters of the release hash>, and one task definition revision per release',
381
+ 'One target group per release, named ductape-<hash>, tagged with the service it serves',
382
+ 'Two load balancer rules per deployment: one for <name>.<domain> that holds the traffic split, and one for <name>--cand.<domain> that also needs a secret header, so only Ductape can reach a release being checked',
383
+ 'One Secrets Manager secret per deployed function, under ductape/, holding its signing key (a service gets none); the execution role injects it into the task',
384
+ ],
385
+ limits: [
386
+ 'A release that has stopped taking traffic keeps running (and costing) until you remove it, unless you switch on --fargate-scale-down-idle on: then releases that are not serving, were not serving just before, and are not being checked are scaled to zero tasks. Ductape never deletes anything, and a scaled-down release comes back at its old size, after a wait, if it is asked for again (a rollback to it is then not instant).',
387
+ 'The load balancer has no access check Ductape can pass to a caller, so a function is protected by its signature check alone. A service is as public as the load balancer: limit who can reach it with a prefix list (step 5). A load balancer with no internet address at all is supported with Scheme=internal: releases are then checked from inside your VPC by a relay function, because Ductape cannot reach it.',
388
+ 'How long one call can take is the load balancer idle timeout, which the stack sets to 15 minutes.',
389
+ 'Runtime settings: cpu, memory and minInstances apply. timeoutSeconds, concurrency and maxInstances do not exist on Fargate and are refused at plan time.',
390
+ ],
391
+ troubleshooting: [
392
+ { problem: 'Validation says the listener is HTTP, not HTTPS', fix: 'Use the ListenerArn output of the ductape-fargate stack, which is HTTPS. Ductape will not send signed requests over plain HTTP.' },
393
+ { problem: 'A new release never becomes healthy', fix: 'Read the service events and the log group /ecs/ductape. The usual causes are a container that does not listen on the declared port (a function listens on 8080), tasks that cannot pull the image because the subnets have no route to the internet (use public subnets, or a NAT gateway with --fargate-private-tasks), or a security group that blocks the load balancer.' },
394
+ { problem: 'The address does not resolve or the certificate is rejected', fix: 'The wildcard DNS record must point at the load balancer and the certificate must cover *.<your domain>. A wildcard certificate does not cover the domain itself or a second level below the first.' },
395
+ { problem: '"is not authorized to perform: iam:PassRole"', fix: 'DuctapeAccess may hand only DuctapeFargateTask and DuctapeFargateExecution to ECS. Complete the connection with exactly those role ARNs.' },
396
+ ],
397
+ };
398
+ /** Extra steps for a connection that also deploys to ECS Express Mode. It builds on the Fargate stack and changes what is guaranteed, which the steps say plainly. */
399
+ export const AWS_EXPRESS_OPTIONAL = {
400
+ title: 'Also deploy to ECS Express Mode (optional)',
401
+ summary: 'ECS Express Mode builds the load balancer, HTTPS and scaling for you, so there is no domain or certificate to bring. It also moves traffic by itself, which means Ductape cannot split traffic or check a release before it takes traffic. Choose it for simplicity; choose Fargate for control.',
402
+ steps: [
403
+ { step: 1, who: 'you', title: 'Do the Fargate steps first', notes: ['Express uses the cluster, the task role and the execution role the ductape-fargate stack creates, and the connection must hold them. You do not need the domain, certificate or DNS record: skip steps 1 and 4 of the Fargate section if you only want Express.'] },
404
+ { step: 2, who: 'ductape', title: 'Get the Express stack', commands: ['ductape cloud connections get <TAG> --save-express-template ductape-ecs-express.yaml'] },
405
+ {
406
+ step: 3, who: 'you', title: 'Create the infrastructure role',
407
+ commands: ['aws cloudformation deploy --stack-name ductape-ecs-express --template-file ductape-ecs-express.yaml --capabilities CAPABILITY_NAMED_IAM --region <REGION>'],
408
+ notes: ['It creates DuctapeExpressInfrastructure, the role AWS assumes to build the load balancer (with the AWS managed policy for that), and attaches the Express permissions to DuctapeAccess.'],
409
+ },
410
+ {
411
+ step: 4, who: 'ductape', title: 'Complete the connection with the role',
412
+ commands: ['aws cloudformation describe-stacks --stack-name ductape-ecs-express --region <REGION> > express.json', 'ductape cloud connections complete <TAG> --express-outputs-file express.json'],
413
+ notes: ['Or give it directly with --express-infrastructure-role-arn.'],
414
+ },
415
+ { step: 5, who: 'ductape', title: 'Validate it', commands: ['ductape cloud connections validate <TAG>'] },
416
+ ],
417
+ creates: [
418
+ 'One task definition revision per release, in the family ductape-<deployment>, with the container named Main and tagged with the release hash',
419
+ 'One Express service per deployment, updated in place. Express makes the load balancer, target groups and security groups for it.',
420
+ 'One Secrets Manager secret per deployed function, under ductape/, holding its signing key (a service gets none)',
421
+ ],
422
+ limits: [
423
+ 'Traffic cannot be split: a plan is refused unless it sends 100 percent. AWS runs its own canary (a small share first, a short bake, then the rest) and rolls back on its own alarm.',
424
+ 'A release cannot be checked before it takes traffic. Ductape checks it once it is serving and returns to the last good release if the check fails. A first release has nothing to return to and stays failed.',
425
+ 'Express checks health over HTTP and the path must answer 200. Set runtime.startupProbe.path (a service can use a verification check that expects 200).',
426
+ 'The address is public unless the subnets are private. A function is protected by its signature check alone.',
427
+ 'Nothing is deleted or scaled down. Services Ductape made stay until you remove them.',
428
+ ],
429
+ troubleshooting: [
430
+ { problem: 'Plan says "cannot split traffic"', fix: 'Use trafficPercent 100, or deploy to aws_fargate to control the split.' },
431
+ { problem: 'Plan says Express needs a health path', fix: 'Set runtime.startupProbe.path to a path that answers 200. A function answers an unsigned call with 401, so give it a path of your own.' },
432
+ { problem: '"AWS rolled the release back"', fix: 'Express rolled the canary back because its health check or error alarm tripped. The message carries AWS\'s reason; the service stays on the last good release.' },
433
+ { problem: 'Validation says the infrastructure role does not trust ECS', fix: 'Create it from the ductape-ecs-express stack. The role must trust ecs.amazonaws.com and carry AmazonECSInfrastructureRoleforExpressGatewayServices.' },
434
+ ],
435
+ };
436
+ export const AZURE_DEPLOY_ROLE_LIST = [
437
+ { role: 'Contributor (or the "Ductape Deploy Operator" custom role)', for: 'on the one resource group you create for Ductape, and nowhere else: add container apps to your environment and build images in your registry' },
438
+ { role: 'AcrPull on the registry, for the runtime identity', for: 'the setup template assigns it, so your container apps can pull the images Ductape builds' },
439
+ ];
440
+ export const AZURE_DEPLOY_CREATES = [
441
+ 'One container app per deployed version of a function or service, named ductape-<workspace>-<name>-<version>-<env>, in your container apps environment',
442
+ 'One revision per release (named <app>--r<hash>), with a cand label for a release being checked; the revision serving traffic is always named explicitly, so a new release never takes traffic by accident',
443
+ 'One image per build in your registry, named <product>-<name>, built by Container Registry Tasks from your Dockerfile',
444
+ 'A sign-in check on each app (Container Apps authentication) so nobody can call it without a token from your own service principal; the app is only opened after that check is in place',
445
+ 'One app secret per deployed function holding its signing key (a service gets none)',
446
+ ];
447
+ export const AZURE_DEPLOY_SAFETY = 'Ductape only adds resources it tags as its own (ductape_managed), never changes or reuses one it did not create, and never deletes anything, including what it created. It never registers resource providers or changes anything outside the one resource group. Removing deployed resources is always your own action.';
448
+ export const AZURE_DEPLOY_TROUBLESHOOTING = [
449
+ { problem: 'Validation lists missing permissions', fix: 'The service principal lacks actions on the resource group. Assign Contributor on it (az role assignment create --assignee <CLIENT_ID> --role Contributor --scope /subscriptions/<SUBSCRIPTION_ID>/resourceGroups/<RESOURCE_GROUP>) or the "Ductape Deploy Operator" role shown by the create response, then validate again. Role changes can take a few minutes.' },
450
+ { problem: '"MissingSubscriptionRegistration" or a resource provider is not registered', fix: 'A subscription owner registers each provider once: az provider register --namespace Microsoft.App --wait (and Microsoft.ContainerRegistry, Microsoft.OperationalInsights, Microsoft.ManagedIdentity). Ductape never changes subscription settings.' },
451
+ { problem: 'Builds fail with "ACR tasks are not permitted" or similar', fix: 'Azure does not run registry builds on free-credit and some trial subscriptions. Use a pay-as-you-go subscription.' },
452
+ { problem: 'A container app cannot pull its image', fix: 'The runtime identity needs AcrPull on the registry. The setup template assigns it; if you made the registry another way, assign AcrPull to the identity yourself. Also check the registry has not turned off Azure Resource Manager tokens (az acr config authentication-as-arm update -r <REGISTRY> --status enabled).' },
453
+ { problem: 'The deployed app answers 401 in a browser', fix: 'That is intended. Apps check sign-in tokens from your service principal; Ductape calls them with one.' },
454
+ { problem: 'The connection says it was not created for deploys', fix: 'Create it with --deploy so it carries the deploy scope.' },
455
+ ];
456
+ export const CLOUDFLARE_DEPLOY_ROLE_LIST = [
457
+ { role: 'Account / Workers Scripts / Edit', for: 'create Worker versions and deployments, and the placeholder that stands in until a release is checked' },
458
+ { role: 'Account / Workers KV Storage / Edit', for: 'keep release bundles in a namespace named ductape-releases until they are deployed' },
459
+ ];
460
+ export const CLOUDFLARE_DEPLOY_CREATES = [
461
+ 'A Workers KV namespace named ductape-releases, where each release bundle waits until it is deployed (the bundle stays in your account; Ductape keeps only its digest)',
462
+ 'One Worker per deployed version of a function, tagged ductape_managed and ductape_workspace',
463
+ 'One Worker version per release, tagged with the release hash, carrying the deployment\'s signing key as a secret binding',
464
+ 'One deployment per traffic change: Cloudflare\'s own gradual rollout, with the percentages you plan',
465
+ 'A workers.dev address for each Worker and a preview address for each version, so a release is called and checked before it takes any traffic',
466
+ ];
467
+ export const CLOUDFLARE_DEPLOY_SAFETY = 'Ductape only adds resources it tags as its own (ductape_managed), never changes or reuses one it did not create, and never deletes anything, including what it created. Removing deployed Workers is always your own action. A Worker has no cloud-level access check in front of it: the function\'s own signature check, which every call must pass, is the access control. Only functions can run on Workers, not services, and only TypeScript functions.';
468
+ export const CLOUDFLARE_DEPLOY_TROUBLESHOOTING = [
469
+ { problem: 'Validation says the token lacks permissions', fix: 'Edit the API token and add Account / Workers Scripts / Edit and Account / Workers KV Storage / Edit, limited to this account, then validate again.' },
470
+ { problem: '"has no workers.dev subdomain"', fix: 'Set one under Workers & Pages in the dashboard. Deployed functions are reached on it.' },
471
+ { problem: '"not in this Cloudflare account (namespace ductape-releases)"', fix: 'Publish the bundle again with ductape deploy releases publish-worker. Releases are published through one connection and deployed through the same one.' },
472
+ { problem: 'A plan says this release is a container image, or a Worker bundle', fix: 'A release is made of one kind of artifact. Bundles run only on cloudflare_workers targets and images only on the others.' },
473
+ { problem: 'A plan is blocked on timeout', fix: 'A Worker is stopped after 30 seconds of CPU time. Lower the contract\'s timeout_ms, or deploy that function to Cloud Run, Lambda or Container Apps.' },
474
+ { problem: 'The cloud refuses cpu, memory or instance settings', fix: 'Cloudflare manages size and scaling. Remove the runtime block from the plan.' },
475
+ { problem: 'Cloudflare only keeps the last 100 versions', fix: 'Rolling back to a release that is older than that fails with a clear message. Publish and deploy it again.' },
476
+ ];
174
477
  export const GCP_DEPLOY_APIS = [
175
478
  'run.googleapis.com', 'cloudbuild.googleapis.com', 'artifactregistry.googleapis.com', 'secretmanager.googleapis.com',
176
479
  'storage.googleapis.com', 'cloudresourcemanager.googleapis.com', 'iam.googleapis.com',
@@ -183,10 +486,17 @@ export function connectionGuide(providerInput, purposeInput = 'resources') {
183
486
  const provider = providerInput;
184
487
  const purpose = purposeInput;
185
488
  const base = { provider, purpose, secrets: SECRETS_RULE };
186
- if (purpose === 'deploy' && provider !== 'gcp') {
489
+ if (purpose === 'resources' && provider === 'cloudflare') {
490
+ return {
491
+ ...base, supported: false,
492
+ summary: 'A Cloudflare connection is for deploying Workers only. Ask for the "deploy" guide: ductape cloud connections guide --provider cloudflare --purpose deploy.',
493
+ steps: [],
494
+ };
495
+ }
496
+ if (purpose === 'deploy' && provider !== 'gcp' && provider !== 'aws' && provider !== 'azure' && provider !== 'cloudflare') {
187
497
  return {
188
498
  ...base, supported: false,
189
- summary: `Deploying code through a ${provider} connection is not available yet. Only GCP (Cloud Run and Cloud Build) has a deploy adapter. A ${provider} connection can still manage resources: ask for the "resources" guide.`,
499
+ summary: `Deploying code through a ${provider} connection is not available yet. Only GCP (Cloud Run and Cloud Build), AWS (Lambda and CodeBuild), Azure (Container Apps and Container Registry Tasks) and Cloudflare (Workers) have a deploy adapter. A ${provider} connection can still manage resources: ask for the "resources" guide.`,
190
500
  steps: [],
191
501
  };
192
502
  }
@@ -246,6 +556,108 @@ export function connectionGuide(providerInput, purposeInput = 'resources') {
246
556
  } : {}),
247
557
  };
248
558
  }
559
+ if (provider === 'cloudflare' && purpose === 'deploy') {
560
+ return {
561
+ ...base, supported: true,
562
+ summary: 'Lets Ductape deploy your TypeScript functions to Cloudflare Workers in your own account, through an API token you create and can read. Workers have no container: you publish a JavaScript bundle.',
563
+ steps: [
564
+ { step: 1, who: 'you', title: 'Find your account id', notes: ['In the Cloudflare dashboard, open Workers & Pages. The account id is on the right and is 32 characters. Make sure the account has a workers.dev subdomain.'] },
565
+ {
566
+ step: 2, who: 'you', title: 'Create an API token with two permissions',
567
+ notes: ['Manage Account, Account API Tokens, Create Token, Create Custom Token. Add Account / Workers Scripts / Edit and Account / Workers KV Storage / Edit, limit it to this account and create it. Cloudflare shows the token once.'],
568
+ },
569
+ { step: 3, who: 'you', title: 'Put the token in an environment variable', commands: ['read -s CLOUDFLARE_API_TOKEN && export CLOUDFLARE_API_TOKEN'], notes: ['This keeps the token out of the command line and shell history.'] },
570
+ { step: 4, who: 'ductape', title: 'Create the connection', commands: ['ductape cloud connections create --provider cloudflare --name "<NAME>" --tag <TAG> --deploy'] },
571
+ { step: 5, who: 'ductape', title: 'Complete it', commands: ['ductape cloud connections complete <TAG> --account-id <ACCOUNT_ID> --api-token-env CLOUDFLARE_API_TOKEN'] },
572
+ { step: 6, who: 'ductape', title: 'Validate it', commands: ['ductape cloud connections validate <TAG>'], notes: ['It checks the token is live, that it can reach Workers and Workers KV, and that the account has a workers.dev subdomain. Write access is proved by the first deploy; if it is missing the message says so.'] },
573
+ ],
574
+ access: { roles: CLOUDFLARE_DEPLOY_ROLE_LIST, apis: [] },
575
+ creates: CLOUDFLARE_DEPLOY_CREATES,
576
+ troubleshooting: CLOUDFLARE_DEPLOY_TROUBLESHOOTING,
577
+ next: [
578
+ 'Publish a release: ductape deploy releases publish-worker --file release.json --connection <TAG> --entry src/index.ts (or --bundle dist/index.js). The file holds product, function, version, contract, config and verification, and no image.',
579
+ 'Plan and apply as usual with a target of kind cloudflare_workers on that connection. Release, plan, approval, canary and rollback work the same as on the other clouds.',
580
+ CLOUDFLARE_DEPLOY_SAFETY,
581
+ ],
582
+ };
583
+ }
584
+ if (provider === 'azure' && purpose === 'deploy') {
585
+ return {
586
+ ...base, supported: true,
587
+ summary: 'Lets Ductape deploy to Azure Container Apps and build source with Container Registry Tasks in your own Azure subscription, through a service principal that can work in one resource group you create.',
588
+ steps: [
589
+ { step: 1, who: 'you', title: 'Choose a location and make a resource group', commands: ['az group create --name ductape-deploy --location <LOCATION>'], notes: ['Pick a location where Container Apps is available (for example uksouth). Everything Ductape adds goes in this one group, so removing it removes it all.', 'Registry builds are refused on free-credit and some trial subscriptions; use a pay-as-you-go subscription.'] },
590
+ { step: 2, who: 'you', title: 'Register the resource providers (a subscription owner, once)', commands: ['az provider register --namespace Microsoft.App --wait', 'az provider register --namespace Microsoft.ContainerRegistry --wait', 'az provider register --namespace Microsoft.OperationalInsights --wait', 'az provider register --namespace Microsoft.ManagedIdentity --wait'], notes: ['Ductape cannot do this for you: it is a subscription-level change.'] },
591
+ {
592
+ step: 3, who: 'ductape', title: 'Create the connection and save the setup template',
593
+ commands: ['ductape cloud connections create --provider azure --name "<NAME>" --tag <TAG> --deploy --save-template ductape-deploy.json'],
594
+ notes: ['The response also holds the custom role definition once the connection knows your resource group. If you lose the file: ductape cloud connections get <TAG> --save-template ductape-deploy.json.'],
595
+ },
596
+ {
597
+ step: 4, who: 'you', title: 'Deploy the template into the resource group',
598
+ commands: ['az deployment group create --resource-group ductape-deploy --template-file ductape-deploy.json --query properties.outputs'],
599
+ notes: ['It creates a user assigned identity for your apps to run as, a container registry, a log workspace and a container apps environment, and lets the identity pull from the registry. Read it first. The role assignment in it needs you to hold Owner or User Access Administrator on the group.', 'The outputs give the registry name, environment name and identity id used in step 6.'],
600
+ },
601
+ {
602
+ step: 5, who: 'you', title: 'Create a service principal that can work in that group only',
603
+ commands: ['az ad sp create-for-rbac --name ductape-deploy --role Contributor --scopes /subscriptions/<SUBSCRIPTION_ID>/resourceGroups/ductape-deploy', 'read -s AZURE_CLIENT_SECRET && export AZURE_CLIENT_SECRET'],
604
+ notes: ['The first command prints appId (the client id), password (the client secret) and tenant. Paste the password into the prompt of the second command so it stays out of the command line and shell history.', 'Prefer less than Contributor? Create the "Ductape Deploy Operator" custom role from the create response and assign that instead. It cannot delete anything, read secrets or assign roles.'],
605
+ },
606
+ {
607
+ step: 6, who: 'ductape', title: 'Complete it',
608
+ commands: ['ductape cloud connections complete <TAG> --tenant-id <TENANT_ID> --subscription-id <SUBSCRIPTION_ID> --client-id <CLIENT_ID> --client-secret-env AZURE_CLIENT_SECRET --default-location <LOCATION> --resource-group ductape-deploy --registry-name <REGISTRY_NAME> --environment-name <ENVIRONMENT_NAME> --runtime-identity-id <RUNTIME_IDENTITY_ID>'],
609
+ },
610
+ { step: 7, who: 'ductape', title: 'Validate it', commands: ['ductape cloud connections validate <TAG>'], notes: ['A failure names each missing permission and each resource provider that is not registered, and checks that the environment, registry and identity are there.'] },
611
+ ],
612
+ access: { roles: AZURE_DEPLOY_ROLE_LIST, apis: [] },
613
+ creates: AZURE_DEPLOY_CREATES,
614
+ troubleshooting: AZURE_DEPLOY_TROUBLESHOOTING,
615
+ next: [
616
+ 'Build and deploy: ductape deploy builds create --file build.json --dir <SOURCE_DIR> --wait (the file names the connection tag and a location such as uksouth). Builds use your Dockerfile, and the folder you upload is the build context.',
617
+ 'See what is deployed: ductape deploy deployments list, or the Deployments section of the product in the workbench.',
618
+ AZURE_DEPLOY_SAFETY,
619
+ ],
620
+ };
621
+ }
622
+ if (provider === 'aws' && purpose === 'deploy') {
623
+ return {
624
+ ...base, supported: true,
625
+ summary: 'Lets Ductape deploy to AWS Lambda and build source in your own AWS account, through IAM roles you create and control.',
626
+ steps: [
627
+ { step: 1, who: 'you', title: 'Choose a region', notes: ['Pick a region where Lambda, Lambda function URLs, CodeBuild and ECR are available (for example eu-west-2). New AWS accounts have lower Lambda memory and concurrency limits and one CodeBuild build at a time; ask for increases in Service Quotas if you need them.'] },
628
+ {
629
+ step: 2, who: 'ductape', title: 'Create the connection and save the setup template',
630
+ commands: ['ductape cloud connections create --provider aws --name "<NAME>" --tag <TAG> --deploy --save-template ductape-deploy.yaml'],
631
+ notes: ['The response also holds the external_id and the same policy as JSON, for anyone who does not use CloudFormation. If you lose the file: ductape cloud connections get <TAG> --save-template ductape-deploy.yaml (until the connection is active).'],
632
+ },
633
+ {
634
+ step: 3, who: 'you', title: 'Create the roles with one CloudFormation stack',
635
+ commands: ['aws cloudformation deploy --stack-name ductape-deploy --template-file ductape-deploy.yaml --capabilities CAPABILITY_NAMED_IAM --region <REGION>'],
636
+ notes: [
637
+ 'It creates DuctapeAccess (the role Ductape assumes, limited to resources named ductape-*), DuctapeFunctionRuntime (the role your functions run as) and DuctapeBuild (the role builds run as). Read the template before you run it: nothing in it can be used by anyone but the Ductape account holding your external id.',
638
+ 'DuctapeFunctionRuntime can write logs and read secrets under ductape/. Add whatever else your functions need to it, for example access to your own tables or queues.',
639
+ 'DuctapeAccess also carries a small second policy, DuctapeDeployReport (tag:GetResources), so that `ductape deploy connections orphans` can list what Ductape made. Deploys do not need it.',
640
+ 'Without CloudFormation, create the three roles yourself: the trust policy for DuctapeAccess is in the create response, and the policy to attach is deploy_setup.policy.',
641
+ ],
642
+ },
643
+ { step: 4, who: 'you', title: 'Let the Ductape integrations principal assume the role', notes: ['If your Ductape installation asks for it, allow its IAM principal to sts:AssumeRole on DuctapeAccess. The trust policy and external id stay as the stack created them.'] },
644
+ {
645
+ step: 5, who: 'ductape', title: 'Complete it with the three roles',
646
+ commands: ['ductape cloud connections complete <TAG> --role-arn arn:aws:iam::<ACCOUNT_ID>:role/DuctapeAccess --runtime-role-arn arn:aws:iam::<ACCOUNT_ID>:role/DuctapeFunctionRuntime --build-role-arn arn:aws:iam::<ACCOUNT_ID>:role/DuctapeBuild --default-region <REGION>'],
647
+ },
648
+ { step: 6, who: 'ductape', title: 'Validate it', commands: ['ductape cloud connections validate <TAG>'], notes: ['A failure names each missing permission and the policy statement that grants it, and checks that the runtime and build roles trust Lambda and CodeBuild.'] },
649
+ ],
650
+ access: { roles: AWS_DEPLOY_ROLE_LIST, apis: [] },
651
+ creates: AWS_DEPLOY_CREATES,
652
+ troubleshooting: AWS_DEPLOY_TROUBLESHOOTING,
653
+ optional: [AWS_FARGATE_OPTIONAL, AWS_EXPRESS_OPTIONAL],
654
+ next: [
655
+ 'Build and deploy: ductape deploy builds create --file build.json --dir <SOURCE_DIR> --wait (the file names the connection tag and a region such as eu-west-2). Builds use your Dockerfile.',
656
+ 'See what is deployed: ductape deploy deployments list, or the Deployments section of the product in the workbench.',
657
+ AWS_DEPLOY_SAFETY,
658
+ ],
659
+ };
660
+ }
249
661
  if (provider === 'aws') {
250
662
  return {
251
663
  ...base, supported: true,
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Reading a project's .env file to find the values that are secrets, so they can be saved to the workspace's secrets (and then used as
3
+ * `{ "secret": "NAME" }` in a release's configuration). Everything here is pure and works on text; nothing here prints, logs or returns a
4
+ * value except `parseDotenv`, whose output stays inside the command and goes only to the workspace. A result meant for a person or an
5
+ * assistant (`describePlan`) carries names, reasons and lengths, never any part of a value.
6
+ */
7
+ export interface IEnvEntry {
8
+ name: string;
9
+ value: string;
10
+ /** 1-based line the entry starts on. */
11
+ line: number;
12
+ /** True when the same name appears again later in the file, which wins. */
13
+ duplicate?: boolean;
14
+ }
15
+ /**
16
+ * Reads dotenv text: `NAME=value`, an optional `export `, single and double quotes (a double-quoted value may span lines and uses \n, \t and \"
17
+ * escapes), `#` comments on their own line or after an unquoted value, and blank lines. A name that is not a valid variable name is skipped.
18
+ * When a name appears more than once the last one wins, as in every dotenv loader.
19
+ */
20
+ export declare function parseDotenv(text: string): IEnvEntry[];
21
+ export type Classification = 'secret' | 'config' | 'skip';
22
+ export interface IClassified {
23
+ name: string;
24
+ classification: Classification;
25
+ /** Why, in words, from the name or the shape of the value. Never the value. */
26
+ reason: string;
27
+ }
28
+ /**
29
+ * Decides whether an entry looks like a secret, from its name and the shape of its value. It is a guide, not a judgement: the person (or the
30
+ * assistant, with the person) chooses what to save, with `--only` and `--all`. A value is only ever looked at, never kept or shown.
31
+ */
32
+ export declare function classifyEntry(entry: IEnvEntry): IClassified;
33
+ export interface IScanOptions {
34
+ /** Save every entry that has a real value, whatever it looks like. */
35
+ all?: boolean;
36
+ /** Save exactly these names, whatever they look like (they must be in the file). */
37
+ only?: string[];
38
+ /** Never save these names. */
39
+ exclude?: string[];
40
+ /** Added in front of each name to make the workspace secret's key. */
41
+ prefix?: string;
42
+ /** Replace a secret that already exists. Without it an existing secret is left alone. */
43
+ overwrite?: boolean;
44
+ }
45
+ export type ScanAction = 'create' | 'update' | 'exists' | 'config' | 'skip' | 'excluded';
46
+ export interface IScanRow extends IClassified {
47
+ /** The key it would be saved under. */
48
+ key: string;
49
+ action: ScanAction;
50
+ /** How long the value is. Not the value. */
51
+ length: number;
52
+ duplicate?: boolean;
53
+ }
54
+ /** What would be saved, and why each of the rest is not. Pure: no value leaves this function except as a length. */
55
+ export declare function planScan(entries: IEnvEntry[], existingKeys: ReadonlySet<string>, options?: IScanOptions): IScanRow[];
56
+ /** What a person or an assistant is shown. Names, the decision, the reason and a length: never any part of a value. */
57
+ export declare function describePlan(rows: IScanRow[], source: string, applied: boolean): Record<string, unknown>;