@gadicc/loom 1.35.3 → 1.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +56 -0
  2. package/THIRD_PARTY_NOTICES.md +12 -9
  3. package/esm/src/cli/externalSkills.d.ts.map +1 -1
  4. package/esm/src/cli/externalSkills.js +25 -20
  5. package/esm/src/cli/mod.d.ts +72 -1
  6. package/esm/src/cli/mod.d.ts.map +1 -1
  7. package/esm/src/cli/mod.js +771 -36
  8. package/esm/src/cli/projectSkills.d.ts +10 -3
  9. package/esm/src/cli/projectSkills.d.ts.map +1 -1
  10. package/esm/src/cli/projectSkills.js +173 -49
  11. package/esm/src/cli/vercelBuildEnv.d.ts +28 -0
  12. package/esm/src/cli/vercelBuildEnv.d.ts.map +1 -1
  13. package/esm/src/cli/vercelBuildEnv.js +120 -30
  14. package/esm/src/next/secrets/mod.d.ts +108 -0
  15. package/esm/src/next/secrets/mod.d.ts.map +1 -0
  16. package/esm/src/next/secrets/mod.js +176 -0
  17. package/esm/src/secrets/encoding.d.ts +32 -0
  18. package/esm/src/secrets/encoding.d.ts.map +1 -0
  19. package/esm/src/secrets/encoding.js +87 -0
  20. package/esm/src/secrets/errors.d.ts +45 -0
  21. package/esm/src/secrets/errors.d.ts.map +1 -0
  22. package/esm/src/secrets/errors.js +39 -0
  23. package/esm/src/secrets/fingerprint.d.ts +43 -0
  24. package/esm/src/secrets/fingerprint.d.ts.map +1 -0
  25. package/esm/src/secrets/fingerprint.js +87 -0
  26. package/esm/src/secrets/frame.d.ts +34 -0
  27. package/esm/src/secrets/frame.d.ts.map +1 -0
  28. package/esm/src/secrets/frame.js +86 -0
  29. package/esm/src/secrets/keyring.d.ts +62 -0
  30. package/esm/src/secrets/keyring.d.ts.map +1 -0
  31. package/esm/src/secrets/keyring.js +160 -0
  32. package/esm/src/secrets/legacy.d.ts +60 -0
  33. package/esm/src/secrets/legacy.d.ts.map +1 -0
  34. package/esm/src/secrets/legacy.js +147 -0
  35. package/esm/src/secrets/maintenance.d.ts +173 -0
  36. package/esm/src/secrets/maintenance.d.ts.map +1 -0
  37. package/esm/src/secrets/maintenance.js +315 -0
  38. package/esm/src/secrets/mod.d.ts +6 -0
  39. package/esm/src/secrets/mod.d.ts.map +1 -0
  40. package/esm/src/secrets/mod.js +5 -0
  41. package/esm/src/secrets/secrets.d.ts +192 -0
  42. package/esm/src/secrets/secrets.d.ts.map +1 -0
  43. package/esm/src/secrets/secrets.js +528 -0
  44. package/package.json +50 -2
  45. package/script/src/cli/externalSkills.d.ts.map +1 -1
  46. package/script/src/cli/externalSkills.js +25 -20
  47. package/script/src/cli/mod.d.ts +72 -1
  48. package/script/src/cli/mod.d.ts.map +1 -1
  49. package/script/src/cli/mod.js +772 -33
  50. package/script/src/cli/projectSkills.d.ts +10 -3
  51. package/script/src/cli/projectSkills.d.ts.map +1 -1
  52. package/script/src/cli/projectSkills.js +173 -49
  53. package/script/src/cli/vercelBuildEnv.d.ts +28 -0
  54. package/script/src/cli/vercelBuildEnv.d.ts.map +1 -1
  55. package/script/src/cli/vercelBuildEnv.js +121 -30
  56. package/script/src/next/secrets/mod.d.ts +108 -0
  57. package/script/src/next/secrets/mod.d.ts.map +1 -0
  58. package/script/src/next/secrets/mod.js +218 -0
  59. package/script/src/secrets/encoding.d.ts +32 -0
  60. package/script/src/secrets/encoding.d.ts.map +1 -0
  61. package/script/src/secrets/encoding.js +95 -0
  62. package/script/src/secrets/errors.d.ts +45 -0
  63. package/script/src/secrets/errors.d.ts.map +1 -0
  64. package/script/src/secrets/errors.js +45 -0
  65. package/script/src/secrets/fingerprint.d.ts +43 -0
  66. package/script/src/secrets/fingerprint.d.ts.map +1 -0
  67. package/script/src/secrets/fingerprint.js +92 -0
  68. package/script/src/secrets/frame.d.ts +34 -0
  69. package/script/src/secrets/frame.d.ts.map +1 -0
  70. package/script/src/secrets/frame.js +91 -0
  71. package/script/src/secrets/keyring.d.ts +62 -0
  72. package/script/src/secrets/keyring.d.ts.map +1 -0
  73. package/script/src/secrets/keyring.js +202 -0
  74. package/script/src/secrets/legacy.d.ts +60 -0
  75. package/script/src/secrets/legacy.d.ts.map +1 -0
  76. package/script/src/secrets/legacy.js +186 -0
  77. package/script/src/secrets/maintenance.d.ts +173 -0
  78. package/script/src/secrets/maintenance.d.ts.map +1 -0
  79. package/script/src/secrets/maintenance.js +323 -0
  80. package/script/src/secrets/mod.d.ts +6 -0
  81. package/script/src/secrets/mod.d.ts.map +1 -0
  82. package/script/src/secrets/mod.js +24 -0
  83. package/script/src/secrets/secrets.d.ts +192 -0
  84. package/script/src/secrets/secrets.d.ts.map +1 -0
  85. package/script/src/secrets/secrets.js +532 -0
  86. package/skills/loom/SKILL.md +74 -222
  87. package/skills/loom/references/dependency-upgrades.md +26 -0
  88. package/skills/loom/references/local-development.md +157 -0
  89. package/skills/loom/references/release-safety.md +118 -0
  90. package/skills/loom/references/release-trusted-sources.md +55 -0
  91. package/skills/loom/references/tools-and-skills.md +83 -0
  92. package/skills/loom-api-keys/SKILL.md +1 -1
  93. package/skills/loom-auth/SKILL.md +7 -60
  94. package/skills/loom-auth/references/secrets-and-rotation.md +61 -0
  95. package/skills/loom-db/SKILL.md +4 -79
  96. package/skills/loom-files/SKILL.md +4 -2
  97. package/skills/loom-files/references/provider-configuration.md +142 -0
  98. package/skills/loom-jobs/SKILL.md +9 -8
  99. package/skills/loom-lingui/SKILL.md +5 -3
  100. package/skills/loom-secrets/SKILL.md +252 -0
  101. package/skills/loom-torvalds-review/SKILL.md +9 -6
  102. package/skills/loom-torvalds-review/references/context-profiles.md +2 -1
  103. package/skills/upgrade-deps/SKILL.md +15 -7
@@ -5,14 +5,34 @@ import { parseEnv } from "node:util";
5
5
  function readJson(path) {
6
6
  return JSON.parse(readFileSync(path, "utf8"));
7
7
  }
8
- function productionEntries(envs, keys) {
9
- const keySet = new Set(keys);
10
- return envs.filter((entry) => {
11
- const targets = Array.isArray(entry.target) ? entry.target : [entry.target];
12
- return typeof entry.key === "string" &&
13
- keySet.has(entry.key) &&
14
- targets.includes("production");
15
- });
8
+ function entryTargets(entry) {
9
+ return Array.isArray(entry.target) ? entry.target : [entry.target];
10
+ }
11
+ function productionEntries(envs, matches) {
12
+ return envs.filter((entry) => typeof entry.key === "string" &&
13
+ matches(entry.key) &&
14
+ entryTargets(entry).includes("production"));
15
+ }
16
+ function compileKeyPattern(source, name) {
17
+ if (typeof source !== "string" || !source) {
18
+ throw new Error(`Environment requirement "${name}" has an invalid keyPattern.`);
19
+ }
20
+ // An odd number of backslashes before the final `$` escapes it.
21
+ const trailingBackslashes = source.slice(0, -1).match(/\\*$/)?.[0].length ??
22
+ 0;
23
+ if (source.length < 2 || !source.startsWith("^") || !source.endsWith("$") ||
24
+ trailingBackslashes % 2 === 1) {
25
+ throw new Error(`Environment requirement "${name}" keyPattern must be anchored with ^ and $: ${source}`);
26
+ }
27
+ try {
28
+ new RegExp(source);
29
+ // Grouping the body keeps a top-level alternative such as `^A|B$` inside
30
+ // the anchors, so it cannot match part of an unrelated variable name.
31
+ return new RegExp(`^(?:${source.slice(1, -1)})$`);
32
+ }
33
+ catch {
34
+ throw new Error(`Environment requirement "${name}" keyPattern is not a valid regular expression: ${source}`);
35
+ }
16
36
  }
17
37
  export function isUsablePulledValue(value) {
18
38
  return Boolean(value?.trim()) &&
@@ -57,29 +77,66 @@ function parsePolicyRequirement(value, index) {
57
77
  const keys = Array.isArray(requirement.keys)
58
78
  ? requirement.keys.filter((key) => typeof key === "string" && Boolean(key))
59
79
  : [];
60
- if (keys.length === 0) {
80
+ const hasPattern = requirement.keyPattern !== undefined;
81
+ if (hasPattern && requirement.keys !== undefined) {
82
+ throw new Error(`Environment requirement "${name}" must have either keys or keyPattern, not both.`);
83
+ }
84
+ if (!hasPattern && keys.length === 0) {
61
85
  throw new Error(`Environment requirement "${name}" has no keys.`);
62
86
  }
87
+ const pattern = hasPattern
88
+ ? compileKeyPattern(requirement.keyPattern, name)
89
+ : undefined;
63
90
  let placeholder;
64
91
  if (requirement.placeholder !== undefined) {
65
92
  if (typeof requirement.placeholder !== "object" ||
66
93
  requirement.placeholder === null ||
67
- typeof requirement.placeholder.key !== "string" ||
68
94
  typeof requirement.placeholder.kind !== "string") {
69
95
  throw new Error(`Environment requirement "${name}" has an invalid placeholder policy.`);
70
96
  }
71
- placeholder = {
72
- key: requirement.placeholder.key,
73
- kind: requirement.placeholder.kind,
74
- };
97
+ if (pattern) {
98
+ // The placeholder goes to each matched variable, so naming one is a
99
+ // mistake rather than something to ignore.
100
+ if (requirement.placeholder.key !== undefined) {
101
+ throw new Error(`Environment requirement "${name}" uses keyPattern, so its placeholder must not name a key.`);
102
+ }
103
+ placeholder = { kind: requirement.placeholder.kind };
104
+ }
105
+ else {
106
+ if (typeof requirement.placeholder.key !== "string") {
107
+ throw new Error(`Environment requirement "${name}" has an invalid placeholder policy.`);
108
+ }
109
+ placeholder = {
110
+ key: requirement.placeholder.key,
111
+ kind: requirement.placeholder.kind,
112
+ };
113
+ }
75
114
  }
115
+ const keySet = new Set(keys);
76
116
  return {
117
+ keyPattern: pattern ? requirement.keyPattern : undefined,
77
118
  keys,
119
+ matches: pattern ? (key) => pattern.test(key) : (key) => keySet.has(key),
78
120
  name,
79
121
  placeholder,
122
+ productionOnly: requirement.productionOnly === true,
80
123
  sensitive: requirement.sensitive === true,
81
124
  };
82
125
  }
126
+ /**
127
+ * Validates a Vercel build environment policy (the app's
128
+ * `.github/vercel-production-env.json`) and returns its requirements. Throws
129
+ * naming the requirement that is wrong.
130
+ */
131
+ export function parseVercelBuildEnvironmentPolicy(policy) {
132
+ const requirements = typeof policy === "object" && policy !== null
133
+ ? policy.requirements
134
+ : undefined;
135
+ if (!Array.isArray(requirements)) {
136
+ throw new Error("Vercel environment policy has no requirements array.");
137
+ }
138
+ return requirements.map((value, index) => parsePolicyRequirement(value, index));
139
+ }
83
140
  /**
84
141
  * Validates required Production variables and fills unreadable Sensitive values
85
142
  * with unique build-only placeholders without replacing readable pulled values.
@@ -95,15 +152,19 @@ export function prepareVercelBuildEnvironment({ envFile, manifestFile, metadataF
95
152
  if (!Array.isArray(envs)) {
96
153
  throw new Error("Vercel metadata did not contain an envs array.");
97
154
  }
98
- if (!Array.isArray(policy.requirements)) {
99
- throw new Error("Vercel environment policy has no requirements array.");
100
- }
155
+ const requirements = parseVercelBuildEnvironmentPolicy(policy);
101
156
  const placeholders = [];
102
- for (const [index, value] of policy.requirements.entries()) {
103
- const requirement = parsePolicyRequirement(value, index);
104
- const entries = productionEntries(envs, requirement.keys);
157
+ const addPlaceholder = (key, kind, requirement) => {
158
+ const placeholder = buildPlaceholder(kind);
159
+ envSource = setEnvValue(envSource, key, placeholder.value);
160
+ pulledValues[key] = placeholder.value;
161
+ placeholders.push({ key, marker: placeholder.marker, requirement });
162
+ io.out(`Added a build-only ${key} placeholder for ${requirement}.`);
163
+ };
164
+ for (const requirement of requirements) {
165
+ const entries = productionEntries(envs, requirement.matches);
105
166
  if (entries.length === 0) {
106
- throw new Error(`Missing Vercel Production variable for ${requirement.name}: ${requirement.keys.join(" or ")}`);
167
+ throw new Error(`Missing Vercel Production variable for ${requirement.name}: ${requirement.keyPattern ?? requirement.keys.join(" or ")}`);
107
168
  }
108
169
  const nonSensitive = entries.filter((entry) => entry.type !== "sensitive");
109
170
  if (requirement.sensitive && nonSensitive.length > 0) {
@@ -111,6 +172,43 @@ export function prepareVercelBuildEnvironment({ envFile, manifestFile, metadataF
111
172
  .map((entry) => entry.key)
112
173
  .join(", ")}`);
113
174
  }
175
+ const shared = entries.filter((entry) => {
176
+ const targets = entryTargets(entry);
177
+ if (targets.length !== 1 || targets[0] !== "production")
178
+ return true;
179
+ // Vercel lists custom environments beside `target`, so a variable
180
+ // attached to one is shared even though it targets only Production.
181
+ // Anything but an absent or empty list counts as shared.
182
+ const custom = entry.customEnvironmentIds;
183
+ return custom !== undefined && custom !== null &&
184
+ !(Array.isArray(custom) && custom.length === 0);
185
+ });
186
+ if (requirement.productionOnly && shared.length > 0) {
187
+ throw new Error(`Vercel Production variable must target Production only for ${requirement.name}: ${shared
188
+ .map((entry) => entry.key)
189
+ .join(", ")}`);
190
+ }
191
+ if (requirement.keyPattern !== undefined) {
192
+ // Every matched variable is needed, not one of several alternatives,
193
+ // so each gets its own verdict and, when unreadable, its own placeholder.
194
+ const matchedKeys = [
195
+ ...new Set(entries.map((entry) => entry.key)),
196
+ ];
197
+ for (const key of matchedKeys) {
198
+ if (isUsablePulledValue(pulledValues[key])) {
199
+ io.out(`Verified ${requirement.name} from vercel pull (${key}).`);
200
+ continue;
201
+ }
202
+ if (entries.some((entry) => entry.key === key && entry.type !== "sensitive")) {
203
+ throw new Error(`Vercel Production variable is empty after pull for ${requirement.name}: ${key}`);
204
+ }
205
+ if (!requirement.placeholder) {
206
+ throw new Error(`Sensitive Vercel Production variable has no build placeholder policy for ${requirement.name}.`);
207
+ }
208
+ addPlaceholder(key, requirement.placeholder.kind, requirement.name);
209
+ }
210
+ continue;
211
+ }
114
212
  const pulledKey = requirement.keys.find((key) => isUsablePulledValue(pulledValues[key]));
115
213
  if (pulledKey) {
116
214
  io.out(`Verified ${requirement.name} from vercel pull (${pulledKey}).`);
@@ -128,15 +226,7 @@ export function prepareVercelBuildEnvironment({ envFile, manifestFile, metadataF
128
226
  io.out(`Preserved pulled ${placeholderKey} for ${requirement.name}.`);
129
227
  continue;
130
228
  }
131
- const placeholder = buildPlaceholder(requirement.placeholder.kind);
132
- envSource = setEnvValue(envSource, placeholderKey, placeholder.value);
133
- pulledValues[placeholderKey] = placeholder.value;
134
- placeholders.push({
135
- key: placeholderKey,
136
- marker: placeholder.marker,
137
- requirement: requirement.name,
138
- });
139
- io.out(`Added a build-only ${placeholderKey} placeholder for ${requirement.name}.`);
229
+ addPlaceholder(placeholderKey, requirement.placeholder.kind, requirement.name);
140
230
  }
141
231
  writeFileSync(envFile, envSource, { mode: 0o600 });
142
232
  writeFileSync(manifestFile, `${JSON.stringify({ placeholders }, null, 2)}\n`, { mode: 0o600 });
@@ -0,0 +1,108 @@
1
+ import "../../../_dnt.polyfills.js";
2
+ import { type CreateSecretsOptions, type SecretKeyring, type Secrets, SecretsKeyError } from "../../secrets/mod.js";
3
+ export * from "../../secrets/mod.js";
4
+ declare const ENVIRONMENTS: readonly ["production", "preview", "development"];
5
+ type NextSecretsEnv = Record<string, string | undefined>;
6
+ /** Deployment environments an expected-key list can be recorded for. */
7
+ export type SecretsEnvironment = (typeof ENVIRONMENTS)[number];
8
+ /** One recorded key as it appears in JSON, before validation. */
9
+ export interface RecordedSecretKey {
10
+ id: number;
11
+ fingerprint: string;
12
+ /** `active`, `decrypt-only` or `retired`; a JSON import types it as string. */
13
+ state: string;
14
+ }
15
+ /**
16
+ * Expected keys per environment, in the shape `loom` records them under
17
+ * `features.secrets.config.keys` in `loom.json`, so that object can be passed
18
+ * straight in. Every list is validated when the secrets are created. An
19
+ * absent or empty list means none was recorded for that environment.
20
+ * Development keys are per machine and gitignored, so they have no list.
21
+ */
22
+ export interface NextSecretsExpectedKeys {
23
+ production?: readonly RecordedSecretKey[] | undefined;
24
+ preview?: readonly RecordedSecretKey[] | undefined;
25
+ }
26
+ /**
27
+ * Variable names, in the shape `loom` records them under
28
+ * `features.secrets.config.env` in `loom.json`.
29
+ */
30
+ export interface NextSecretsVariables {
31
+ keyPrefix?: string | undefined;
32
+ activeKeyName?: string | undefined;
33
+ }
34
+ /** Options for {@link createNextSecrets}. */
35
+ export interface CreateNextSecretsOptions extends Omit<CreateSecretsOptions, "keys" | "expectedKeys"> {
36
+ /** Defaults to the environment keyring (`LOOM_SECRETS_KEY_<n>`). */
37
+ keys?: SecretKeyring | undefined;
38
+ /** Variable names for the default keyring. Ignored when `keys` is given. */
39
+ variables?: NextSecretsVariables | undefined;
40
+ expectedKeys?: NextSecretsExpectedKeys | undefined;
41
+ /**
42
+ * Which environment's key list applies. Defaults to the
43
+ * `LOOM_SECRETS_ENVIRONMENT` variable, then `VERCEL_ENV`. A host that
44
+ * provides neither must set one of them: otherwise production cannot be
45
+ * told from development, and a recorded list would be silently ignored.
46
+ * When the two variables name different environments every operation is
47
+ * refused; passing this option skips that comparison.
48
+ */
49
+ environment?: SecretsEnvironment | undefined;
50
+ /**
51
+ * Allow `assertReady()` to pass in production when no key list is recorded.
52
+ * Off by default: in production, a missing list means nothing shows that
53
+ * the deployed key is the one the operator saved.
54
+ */
55
+ allowUnverifiedProduction?: boolean | undefined;
56
+ /**
57
+ * Allow secrets to be used while `next build` prerenders. Off by default: a
58
+ * page prerendered at build time would bake a decrypted value, or an
59
+ * "unreadable" state, into static output, and release builds substitute
60
+ * placeholders for keys they cannot read. Do not set it to make a failing
61
+ * build pass; make the route dynamic instead.
62
+ */
63
+ allowDuringBuild?: boolean | undefined;
64
+ /**
65
+ * The environment object the default keyring reads key values from.
66
+ * Defaults to `process.env`. It is not the manifest's `env` section, which
67
+ * holds variable names and belongs in `variables`, and it is not where the
68
+ * build phase or the deployment environment is read from: see `runtimeEnv`.
69
+ */
70
+ keysEnv?: NextSecretsEnv | undefined;
71
+ /**
72
+ * Where `NEXT_PHASE`, `LOOM_SECRETS_ENVIRONMENT`, `VERCEL_ENV` and
73
+ * `NODE_ENV` are read from. Defaults to
74
+ * `process.env`. For tests only: an app that narrows its environment into
75
+ * its own object must not hide these from the checks that depend on them.
76
+ */
77
+ runtimeEnv?: NextSecretsEnv | undefined;
78
+ }
79
+ /**
80
+ * Secrets were used while `next build` was prerendering. Make the route
81
+ * dynamic, so that it runs per request with the deployment's real keys.
82
+ */
83
+ export declare class SecretsBuildPhaseError extends SecretsKeyError {
84
+ constructor();
85
+ }
86
+ /** Names the environment explicitly where `VERCEL_ENV` is not available. */
87
+ export declare const SECRETS_ENVIRONMENT_ENV = "LOOM_SECRETS_ENVIRONMENT";
88
+ /**
89
+ * The environment whose expected-key list applies, or `null` when it cannot
90
+ * be told. `LOOM_SECRETS_ENVIRONMENT` wins over `VERCEL_ENV`: set it on hosts
91
+ * other than Vercel, and to `development` in `.env.local` to run a production
92
+ * build locally. When both are set and disagree this still returns the
93
+ * explicit one, but `createNextSecrets` refuses every operation.
94
+ */
95
+ export declare function resolveSecretsEnvironment(env?: NextSecretsEnv): SecretsEnvironment | null;
96
+ /**
97
+ * Creates secrets for a Next.js app.
98
+ *
99
+ * It applies the expected-key list for the current deployment environment, and
100
+ * while `next build` prerenders it refuses every operation, including the
101
+ * `tryOpen` variants, with {@link SecretsBuildPhaseError}. A route that uses
102
+ * secrets or calls `assertReady()` must therefore be dynamic.
103
+ *
104
+ * The refusal covers `next build` only. A route that caches its output at run
105
+ * time (`revalidate`, `use cache`) will cache whatever it decrypted.
106
+ */
107
+ export declare function createNextSecrets(options?: CreateNextSecretsOptions): Secrets;
108
+ //# sourceMappingURL=mod.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.d.ts","sourceRoot":"","sources":["../../../../src/src/next/secrets/mod.ts"],"names":[],"mappings":"AAAA,OAAO,4BAA4B,CAAC;AAEpC,OAAO,EAEL,KAAK,oBAAoB,EAIzB,KAAK,aAAa,EAElB,KAAK,OAAO,EACZ,eAAe,EAEhB,MAAM,sBAAsB,CAAC;AAE9B,cAAc,sBAAsB,CAAC;AAQrC,QAAA,MAAM,YAAY,mDAAoD,CAAC;AAEvE,KAAK,cAAc,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC;AAEzD,wEAAwE;AACxE,MAAM,MAAM,kBAAkB,GAAG,CAAC,OAAO,YAAY,CAAC,CAAC,MAAM,CAAC,CAAC;AAE/D,iEAAiE;AACjE,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,WAAW,EAAE,MAAM,CAAC;IACpB,+EAA+E;IAC/E,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;;;;;GAMG;AACH,MAAM,WAAW,uBAAuB;IACtC,UAAU,CAAC,EAAE,SAAS,iBAAiB,EAAE,GAAG,SAAS,CAAC;IACtD,OAAO,CAAC,EAAE,SAAS,iBAAiB,EAAE,GAAG,SAAS,CAAC;CACpD;AAED;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC/B,aAAa,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACpC;AAED,6CAA6C;AAC7C,MAAM,WAAW,wBACf,SAAQ,IAAI,CAAC,oBAAoB,EAAE,MAAM,GAAG,cAAc,CAAC;IAC3D,oEAAoE;IACpE,IAAI,CAAC,EAAE,aAAa,GAAG,SAAS,CAAC;IACjC,4EAA4E;IAC5E,SAAS,CAAC,EAAE,oBAAoB,GAAG,SAAS,CAAC;IAC7C,YAAY,CAAC,EAAE,uBAAuB,GAAG,SAAS,CAAC;IACnD;;;;;;;OAOG;IACH,WAAW,CAAC,EAAE,kBAAkB,GAAG,SAAS,CAAC;IAC7C;;;;OAIG;IACH,yBAAyB,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAChD;;;;;;OAMG;IACH,gBAAgB,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IACvC;;;;;OAKG;IACH,OAAO,CAAC,EAAE,cAAc,GAAG,SAAS,CAAC;IACrC;;;;;OAKG;IACH,UAAU,CAAC,EAAE,cAAc,GAAG,SAAS,CAAC;CACzC;AAED;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,eAAe;;CAO1D;AAoBD,4EAA4E;AAC5E,eAAO,MAAM,uBAAuB,6BAA6B,CAAC;AAElE;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CACvC,GAAG,GAAE,cAA6B,GACjC,kBAAkB,GAAG,IAAI,CAgB3B;AAiCD;;;;;;;;;;GAUG;AACH,wBAAgB,iBAAiB,CAC/B,OAAO,GAAE,wBAA6B,GACrC,OAAO,CA2GT"}
@@ -0,0 +1,176 @@
1
+ import "../../../_dnt.polyfills.js";
2
+ import * as dntShim from "../../../_dnt.shims.js";
3
+ import { createSecrets, envKeyring, parseExpectedSecretKeys, SecretsKeyError, } from "../../secrets/mod.js";
4
+ export * from "../../secrets/mod.js";
5
+ /**
6
+ * The value of `NEXT_PHASE` in the workers that collect page data and
7
+ * prerender during `next build`. Nothing sets it for `next start`, `next dev`
8
+ * or a deployed function.
9
+ */
10
+ const PRODUCTION_BUILD_PHASE = "phase-production-build";
11
+ const ENVIRONMENTS = ["production", "preview", "development"];
12
+ /**
13
+ * Secrets were used while `next build` was prerendering. Make the route
14
+ * dynamic, so that it runs per request with the deployment's real keys.
15
+ */
16
+ export class SecretsBuildPhaseError extends SecretsKeyError {
17
+ constructor() {
18
+ super("Secrets are not available while `next build` prerenders. Make the route dynamic.");
19
+ this.name = "SecretsBuildPhaseError";
20
+ }
21
+ }
22
+ function processEnv() {
23
+ try {
24
+ return dntShim.dntGlobalThis.process
25
+ ?.env ?? {};
26
+ }
27
+ catch {
28
+ // Some runtimes refuse environment access without a permission.
29
+ return {};
30
+ }
31
+ }
32
+ function read(env, name) {
33
+ try {
34
+ return env[name];
35
+ }
36
+ catch {
37
+ return undefined;
38
+ }
39
+ }
40
+ /** Names the environment explicitly where `VERCEL_ENV` is not available. */
41
+ export const SECRETS_ENVIRONMENT_ENV = "LOOM_SECRETS_ENVIRONMENT";
42
+ /**
43
+ * The environment whose expected-key list applies, or `null` when it cannot
44
+ * be told. `LOOM_SECRETS_ENVIRONMENT` wins over `VERCEL_ENV`: set it on hosts
45
+ * other than Vercel, and to `development` in `.env.local` to run a production
46
+ * build locally. When both are set and disagree this still returns the
47
+ * explicit one, but `createNextSecrets` refuses every operation.
48
+ */
49
+ export function resolveSecretsEnvironment(env = processEnv()) {
50
+ const explicit = read(env, SECRETS_ENVIRONMENT_ENV);
51
+ if (explicit !== undefined && explicit !== "") {
52
+ if (!ENVIRONMENTS.includes(explicit)) {
53
+ throw new TypeError(`${SECRETS_ENVIRONMENT_ENV} must be production, preview or development.`);
54
+ }
55
+ return explicit;
56
+ }
57
+ // `NODE_ENV` is "production" in preview builds too, so it cannot tell a
58
+ // preview from production. Vercel's own variable can.
59
+ const vercelEnv = read(env, "VERCEL_ENV");
60
+ return ENVIRONMENTS.includes(vercelEnv)
61
+ ? vercelEnv
62
+ : null;
63
+ }
64
+ function recordedList(expectedKeys, environment) {
65
+ const recorded = expectedKeys?.[environment];
66
+ if (recorded === undefined) {
67
+ return undefined;
68
+ }
69
+ if (!Array.isArray(recorded)) {
70
+ throw new TypeError(`The ${environment} key list must be an array.`);
71
+ }
72
+ return recorded.length === 0 ? undefined : parseExpectedSecretKeys(recorded);
73
+ }
74
+ const GUARDED_METHODS = [
75
+ "seal",
76
+ "sealJson",
77
+ "sealBytes",
78
+ "open",
79
+ "openJson",
80
+ "openBytes",
81
+ "tryOpen",
82
+ "tryOpenJson",
83
+ "tryOpenBytes",
84
+ "needsReseal",
85
+ "reseal",
86
+ "mac",
87
+ "macMatches",
88
+ "macNeedsRefresh",
89
+ ];
90
+ /**
91
+ * Creates secrets for a Next.js app.
92
+ *
93
+ * It applies the expected-key list for the current deployment environment, and
94
+ * while `next build` prerenders it refuses every operation, including the
95
+ * `tryOpen` variants, with {@link SecretsBuildPhaseError}. A route that uses
96
+ * secrets or calls `assertReady()` must therefore be dynamic.
97
+ *
98
+ * The refusal covers `next build` only. A route that caches its output at run
99
+ * time (`revalidate`, `use cache`) will cache whatever it decrypted.
100
+ */
101
+ export function createNextSecrets(options = {}) {
102
+ const { allowDuringBuild, allowUnverifiedProduction, environment, expectedKeys, keys, keysEnv, runtimeEnv, variables, ...rest } = options;
103
+ if (environment !== undefined && !ENVIRONMENTS.includes(environment)) {
104
+ throw new TypeError("environment must be production, preview or development.");
105
+ }
106
+ // Both lists are validated now, whatever the current environment, so a
107
+ // malformed production list fails a local build instead of the first
108
+ // production request.
109
+ const lists = {
110
+ production: recordedList(expectedKeys, "production"),
111
+ preview: recordedList(expectedKeys, "preview"),
112
+ };
113
+ const runtime = () => runtimeEnv ?? processEnv();
114
+ const resolved = environment ?? resolveSecretsEnvironment(runtime());
115
+ const applied = resolved === "production" || resolved === "preview"
116
+ ? lists[resolved]
117
+ : undefined;
118
+ /** Throws when secrets must not be used right now. */
119
+ function guard() {
120
+ if (!allowDuringBuild &&
121
+ read(runtime(), "NEXT_PHASE") === PRODUCTION_BUILD_PHASE) {
122
+ throw new SecretsBuildPhaseError();
123
+ }
124
+ // An explicit variable that contradicts the platform's own would quietly
125
+ // drop the platform's key list (`development` on a production deployment,
126
+ // for example from a `.env.local` that reached the image), so neither is
127
+ // trusted. An `environment` option is the app's own decision and is not
128
+ // second-guessed.
129
+ if (environment === undefined) {
130
+ const explicit = read(runtime(), SECRETS_ENVIRONMENT_ENV);
131
+ const vercelEnv = read(runtime(), "VERCEL_ENV");
132
+ if (ENVIRONMENTS.includes(explicit) &&
133
+ ENVIRONMENTS.includes(vercelEnv) &&
134
+ explicit !== vercelEnv) {
135
+ throw new SecretsKeyError(`${SECRETS_ENVIRONMENT_ENV} is ${explicit} but VERCEL_ENV is ${vercelEnv}. Secrets are refused until the two name the same environment.`);
136
+ }
137
+ }
138
+ // Lists are recorded, but nothing says which environment this is while
139
+ // the process claims to be production: ignoring them here would look
140
+ // exactly like a healthy, verified deployment.
141
+ if (resolved === null &&
142
+ read(runtime(), "NODE_ENV") === "production" &&
143
+ (lists.production !== undefined || lists.preview !== undefined)) {
144
+ throw new SecretsKeyError(`Key fingerprints are recorded but the deployment environment is unknown. Set ${SECRETS_ENVIRONMENT_ENV} to production, preview or development.`);
145
+ }
146
+ }
147
+ const inner = createSecrets({
148
+ ...rest,
149
+ expectedKeys: applied,
150
+ keys: keys ?? envKeyring({ ...variables, env: keysEnv }),
151
+ });
152
+ async function assertReady() {
153
+ guard();
154
+ const readiness = await inner.assertReady();
155
+ if (resolved === "production" && !readiness.verified &&
156
+ !allowUnverifiedProduction) {
157
+ throw new SecretsKeyError("No production key list is recorded, so the deployed key cannot be verified. Record its fingerprint in loom.json.");
158
+ }
159
+ return readiness;
160
+ }
161
+ return {
162
+ assertReady,
163
+ purpose(name, purposeOptions) {
164
+ const purpose = inner.purpose(name, purposeOptions);
165
+ const guarded = {};
166
+ for (const method of GUARDED_METHODS) {
167
+ // deno-lint-ignore require-await -- async so the guard rejects.
168
+ guarded[method] = async (...args) => {
169
+ guard();
170
+ return purpose[method](...args);
171
+ };
172
+ }
173
+ return { ...purpose, ...guarded, assertReady };
174
+ },
175
+ };
176
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Rejects strings that UTF-8 encoding would silently change.
3
+ *
4
+ * `TextEncoder` turns every lone surrogate into U+FFFD, so two different
5
+ * JavaScript strings could otherwise produce the same bytes and collide as
6
+ * bindings or fingerprint input.
7
+ */
8
+ export declare function assertWellFormed(value: string, what: string): string;
9
+ /** UTF-8 bytes of a well-formed string. */
10
+ export declare function encodeUtf8(value: string, what: string): Uint8Array<ArrayBuffer>;
11
+ /** Strict UTF-8 decoding. Throws on malformed input; preserves a leading BOM. */
12
+ export declare function decodeUtf8(bytes: Uint8Array): string;
13
+ /** Unpadded base64url. */
14
+ export declare function toBase64Url(bytes: Uint8Array): string;
15
+ /**
16
+ * Decodes unpadded base64url, accepting only the canonical spelling.
17
+ *
18
+ * Decoders tolerate padding, the standard alphabet and non-zero trailing bits.
19
+ * Re-encoding and comparing leaves exactly one accepted string per byte
20
+ * sequence, so a stored ciphertext cannot be respelled.
21
+ */
22
+ export declare function fromBase64Url(text: string): Uint8Array<ArrayBuffer> | null;
23
+ /**
24
+ * Pre-authentication encoding, as in PASETO: a little-endian 64-bit count of
25
+ * pieces, then each piece prefixed with its little-endian 64-bit byte length.
26
+ *
27
+ * Joining fields with a separator is ambiguous whenever a field can contain
28
+ * the separator. Length prefixes make the encoding injective, so no two
29
+ * different lists of pieces produce the same bytes.
30
+ */
31
+ export declare function pae(pieces: readonly (string | Uint8Array)[]): Uint8Array<ArrayBuffer>;
32
+ //# sourceMappingURL=encoding.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encoding.d.ts","sourceRoot":"","sources":["../../../src/src/secrets/encoding.ts"],"names":[],"mappings":"AAQA;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAQpE;AAED,2CAA2C;AAC3C,wBAAgB,UAAU,CACxB,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,MAAM,GACX,UAAU,CAAC,WAAW,CAAC,CAEzB;AAED,iFAAiF;AACjF,wBAAgB,UAAU,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAEpD;AAED,0BAA0B;AAC1B,wBAAgB,WAAW,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAWrD;AAED;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,CAAC,WAAW,CAAC,GAAG,IAAI,CAe1E;AAED;;;;;;;GAOG;AACH,wBAAgB,GAAG,CACjB,MAAM,EAAE,SAAS,CAAC,MAAM,GAAG,UAAU,CAAC,EAAE,GACvC,UAAU,CAAC,WAAW,CAAC,CAezB"}
@@ -0,0 +1,87 @@
1
+ const encoder = new TextEncoder();
2
+ // `ignoreBOM: true` keeps a leading U+FEFF in the output; the default strips it.
3
+ const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
4
+ const BASE64URL_PATTERN = /^[A-Za-z0-9_-]*$/;
5
+ // Stay well under engine argument limits when spreading into fromCharCode.
6
+ const BINARY_CHUNK = 0x8000;
7
+ /**
8
+ * Rejects strings that UTF-8 encoding would silently change.
9
+ *
10
+ * `TextEncoder` turns every lone surrogate into U+FFFD, so two different
11
+ * JavaScript strings could otherwise produce the same bytes and collide as
12
+ * bindings or fingerprint input.
13
+ */
14
+ export function assertWellFormed(value, what) {
15
+ if (typeof value !== "string") {
16
+ throw new TypeError(`${what} must be a string.`);
17
+ }
18
+ if (!value.isWellFormed()) {
19
+ throw new TypeError(`${what} must be well-formed Unicode.`);
20
+ }
21
+ return value;
22
+ }
23
+ /** UTF-8 bytes of a well-formed string. */
24
+ export function encodeUtf8(value, what) {
25
+ return encoder.encode(assertWellFormed(value, what));
26
+ }
27
+ /** Strict UTF-8 decoding. Throws on malformed input; preserves a leading BOM. */
28
+ export function decodeUtf8(bytes) {
29
+ return decoder.decode(bytes);
30
+ }
31
+ /** Unpadded base64url. */
32
+ export function toBase64Url(bytes) {
33
+ let binary = "";
34
+ for (let offset = 0; offset < bytes.length; offset += BINARY_CHUNK) {
35
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + BINARY_CHUNK));
36
+ }
37
+ return btoa(binary)
38
+ .replaceAll("+", "-")
39
+ .replaceAll("/", "_")
40
+ .replace(/=+$/, "");
41
+ }
42
+ /**
43
+ * Decodes unpadded base64url, accepting only the canonical spelling.
44
+ *
45
+ * Decoders tolerate padding, the standard alphabet and non-zero trailing bits.
46
+ * Re-encoding and comparing leaves exactly one accepted string per byte
47
+ * sequence, so a stored ciphertext cannot be respelled.
48
+ */
49
+ export function fromBase64Url(text) {
50
+ if (!BASE64URL_PATTERN.test(text)) {
51
+ return null;
52
+ }
53
+ let binary;
54
+ try {
55
+ binary = atob(text.replaceAll("-", "+").replaceAll("_", "/"));
56
+ }
57
+ catch {
58
+ return null;
59
+ }
60
+ const bytes = new Uint8Array(binary.length);
61
+ for (let index = 0; index < binary.length; index += 1) {
62
+ bytes[index] = binary.charCodeAt(index);
63
+ }
64
+ return toBase64Url(bytes) === text ? bytes : null;
65
+ }
66
+ /**
67
+ * Pre-authentication encoding, as in PASETO: a little-endian 64-bit count of
68
+ * pieces, then each piece prefixed with its little-endian 64-bit byte length.
69
+ *
70
+ * Joining fields with a separator is ambiguous whenever a field can contain
71
+ * the separator. Length prefixes make the encoding injective, so no two
72
+ * different lists of pieces produce the same bytes.
73
+ */
74
+ export function pae(pieces) {
75
+ const encoded = pieces.map((piece) => piece instanceof Uint8Array ? piece : encodeUtf8(piece, "Encoded piece"));
76
+ const length = encoded.reduce((total, piece) => total + 8 + piece.length, 8);
77
+ const output = new Uint8Array(length);
78
+ const view = new DataView(output.buffer);
79
+ view.setBigUint64(0, BigInt(encoded.length), true);
80
+ let offset = 8;
81
+ for (const piece of encoded) {
82
+ view.setBigUint64(offset, BigInt(piece.length), true);
83
+ output.set(piece, offset + 8);
84
+ offset += 8 + piece.length;
85
+ }
86
+ return output;
87
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Why a sealed value could not be opened.
3
+ *
4
+ * For operator logs and metrics only. Forwarding it to an end user tells a
5
+ * caller who submits tokens which key ids exist and whether a guess reached
6
+ * the cipher.
7
+ */
8
+ export type SecretFailureReason =
9
+ /** Not a string this module could have produced, or the wrong kind. */
10
+ "malformed"
11
+ /** The key version named in the string is not configured. */
12
+ | "unknown-key"
13
+ /** The key version is configured but its value cannot be used. */
14
+ | "key-unavailable"
15
+ /** The key's fingerprint is not the one recorded for that version. */
16
+ | "key-mismatch"
17
+ /** Wrong key, wrong purpose, wrong binding, or altered ciphertext. */
18
+ | "authentication"
19
+ /** The value carried an expiry that has passed. */
20
+ | "expired";
21
+ /**
22
+ * Thrown by `open` for every failure. The message is fixed so that nothing
23
+ * about the cause, the ciphertext or the binding can leak through it.
24
+ */
25
+ export declare class SecretUnreadableError extends Error {
26
+ /** See {@link SecretFailureReason}. Not for end users. */
27
+ readonly reason: SecretFailureReason;
28
+ constructor(reason: SecretFailureReason);
29
+ }
30
+ /**
31
+ * A key is missing or unusable. The message names the variable or key version
32
+ * and the problem, never the value.
33
+ */
34
+ export declare class SecretsKeyError extends Error {
35
+ constructor(message: string);
36
+ }
37
+ /**
38
+ * A configured key is not the key that was recorded for its version: its
39
+ * fingerprint differs. Usually a paste mistake, or a version number reused
40
+ * for a new key.
41
+ */
42
+ export declare class SecretsKeyMismatchError extends SecretsKeyError {
43
+ constructor(message: string);
44
+ }
45
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../src/src/secrets/errors.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,MAAM,mBAAmB;AAC7B,uEAAuE;AACrE,WAAW;AACb,6DAA6D;GAC3D,aAAa;AACf,kEAAkE;GAChE,iBAAiB;AACnB,sEAAsE;GACpE,cAAc;AAChB,sEAAsE;GACpE,gBAAgB;AAClB,mDAAmD;GACjD,SAAS,CAAC;AAEd;;;GAGG;AACH,qBAAa,qBAAsB,SAAQ,KAAK;IAC9C,0DAA0D;IAC1D,QAAQ,CAAC,MAAM,EAAE,mBAAmB,CAAC;gBAEzB,MAAM,EAAE,mBAAmB;CAKxC;AAED;;;GAGG;AACH,qBAAa,eAAgB,SAAQ,KAAK;gBAC5B,OAAO,EAAE,MAAM;CAI5B;AAED;;;;GAIG;AACH,qBAAa,uBAAwB,SAAQ,eAAe;gBAC9C,OAAO,EAAE,MAAM;CAI5B"}