@foxtware/mineral 0.1.5 → 0.1.7
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.
- package/.creds.yml.sample +4 -1
- package/.env.sample +2 -0
- package/.gcloudignore +1 -4
- package/README.md +6 -1
- package/_build_scripts/createNewFunction.js +248 -38
- package/api/shopify/shopifyDecodeSessionToken.js +206 -0
- package/api/slack/slack.constants.js +5 -0
- package/api/slack/slack.utils.js +46 -0
- package/api/slack/slackMessagePost.js +85 -0
- package/api/utils.js +2 -4
- package/bin/mineral.js +1 -1
- package/{.hosting.yml.sample → hosting/.hosting.yml.sample} +4 -7
- package/hosting/copyCredsToEnv.js +48 -0
- package/{_deploy_scripts → hosting}/deployFromHostingYml.js +16 -37
- package/hosting/generateHosted.js +87 -0
- package/{handlerPaths.js → hosting/handlerPaths.js} +1 -1
- package/{hosting.utils.js → hosting/hosting.utils.js} +47 -52
- package/{wrappers.js → hosting/wrappers.js} +2 -2
- package/package.json +2 -2
- package/server.js +3 -6
- package/server.utils.js +41 -7
- package/_build_scripts/copyCredsToEnv.js +0 -45
- package/_deploy_scripts/generateHosted.js +0 -58
- /package/{_deploy_scripts → hosting}/execCommand.js +0 -0
- /package/{_deploy_scripts → hosting}/setEnvVarsGcloud.js +0 -0
package/.creds.yml.sample
CHANGED
package/.env.sample
ADDED
package/.gcloudignore
CHANGED
|
@@ -7,11 +7,8 @@
|
|
|
7
7
|
# $ gcloud topic gcloudignore
|
|
8
8
|
#
|
|
9
9
|
.gcloudignore
|
|
10
|
-
# If you would like to upload your .git directory, .gitignore file or files
|
|
11
|
-
# from your .gitignore file, remove the corresponding line
|
|
12
|
-
# below:
|
|
13
10
|
.git
|
|
14
11
|
.gitignore
|
|
15
12
|
|
|
16
13
|
node_modules
|
|
17
|
-
|
|
14
|
+
.creds.yml
|
package/README.md
CHANGED
|
@@ -51,4 +51,9 @@ The [bedrock](https://github.com/GorgonFreeman/bedrock) middleware, refactored f
|
|
|
51
51
|
- **Monorepo structure**
|
|
52
52
|
Mineral gets pushed to from a larger repo that can also contain private functions. Mineral should be strictly useful stuff for the public, and can be used standalone, but needs to be instantiated for serving, setting stuff like which creds file to use. This allows it to be used as part of another repo in the same HTTP/curl way as by itself. Pass `--workspace` to locate `.creds.yml` and `--api_dirs` to serve additional function directories.
|
|
53
53
|
|
|
54
|
-
For cloud deploy, workspaces use
|
|
54
|
+
For cloud deploy, workspaces use `hosting/.hosting.yml` and `npm run host` (same `--workspace` / `--api_dirs` flags as dev/serve). See `hosting/.hosting.yml.sample`.
|
|
55
|
+
|
|
56
|
+
## What the thang do
|
|
57
|
+
- Server makes functions available from the api/ route, where an export matches the filename. Run `npm run serve`, and they're all curlable.
|
|
58
|
+
- .creds.yml is copied into .env when deploying, so creds can be accessed while hosted. Locally, it reads from the file directly.
|
|
59
|
+
- Cloud deploy reads `hosting/.hosting.yml` for per-function config — `before_wrappers` / `after_wrappers` like `requireHostedApiKey`, `max_instances`, schedules — and deploys each function to Google Cloud.
|
|
@@ -3,31 +3,51 @@ const path = require('path');
|
|
|
3
3
|
const { spawn } = require('child_process');
|
|
4
4
|
const { askQuestion, capitaliseString } = require('../api/utils');
|
|
5
5
|
|
|
6
|
-
const
|
|
7
|
-
const
|
|
6
|
+
const mineralRoot = path.join(__dirname, '..');
|
|
7
|
+
const mineralApiDirectory = path.join(mineralRoot, 'api');
|
|
8
|
+
const rootExampleJsPath = path.join(mineralApiDirectory, '_example.js');
|
|
8
9
|
|
|
9
10
|
const excludedDirs = new Set([
|
|
10
11
|
'node_modules',
|
|
11
12
|
]);
|
|
12
13
|
|
|
13
|
-
const
|
|
14
|
+
const normalizePath = (dirPath) => dirPath.replace(/\/$/, '');
|
|
15
|
+
|
|
16
|
+
const isMineralCwd = () => normalizePath(process.cwd()) === normalizePath(mineralRoot);
|
|
17
|
+
|
|
18
|
+
const getContext = () => {
|
|
19
|
+
const inMineral = isMineralCwd();
|
|
20
|
+
|
|
21
|
+
return {
|
|
22
|
+
inMineral,
|
|
23
|
+
apiDirectory: inMineral ? mineralApiDirectory : path.join(process.cwd(), 'api'),
|
|
24
|
+
mineralApiDirectory,
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const printHelp = (context) => {
|
|
29
|
+
const templateHelp = context.inMineral
|
|
30
|
+
? `example template to copy (default: _example.js in dir, else api/_example.js)
|
|
31
|
+
examples: _example.js, getsingle, _example.getsingle.js`
|
|
32
|
+
: `mineral example template to copy (default: _example.js)
|
|
33
|
+
examples: _example.js, shopify/_example.js, shopify/getsingle`;
|
|
34
|
+
|
|
14
35
|
console.log(`
|
|
15
36
|
Usage:
|
|
16
37
|
npm run new
|
|
17
38
|
npm run new -- --dir <apiSubdir> --name <name> [--template <exampleTemplate>] [--commit]
|
|
18
39
|
|
|
19
40
|
Options:
|
|
20
|
-
--dir, -d api subdirectory (e.g. peoplevox, shopify)
|
|
41
|
+
--dir, -d api subdirectory (e.g. peoplevox, shopify). Omit for flat api/ dirs.
|
|
21
42
|
--name, -n function name suffix (e.g. orderGet → peoplevoxOrderGet)
|
|
22
|
-
--template, -t
|
|
23
|
-
examples: _example.js, getsingle, _example.getsingle.js
|
|
43
|
+
--template, -t ${ templateHelp }
|
|
24
44
|
--commit auto-commit the stub after creation
|
|
25
45
|
--help, -h show this help
|
|
26
46
|
|
|
27
47
|
Examples:
|
|
28
48
|
npm run new -- --dir peoplevox --name orderGet
|
|
29
|
-
npm run new -- --dir peoplevox --name orderGet --template _example.js
|
|
30
49
|
npm run new -- --dir shopify --name pageGet --template getsingle
|
|
50
|
+
npm run new -- --name geodeBye --template shopify/_example.js
|
|
31
51
|
`);
|
|
32
52
|
};
|
|
33
53
|
|
|
@@ -124,11 +144,51 @@ const findExampleFiles = async (dirPath) => {
|
|
|
124
144
|
}
|
|
125
145
|
};
|
|
126
146
|
|
|
147
|
+
const collectMineralExampleFiles = async (dirPath, relativePrefix = '') => {
|
|
148
|
+
const results = [];
|
|
149
|
+
const localExamples = await findExampleFiles(dirPath);
|
|
150
|
+
|
|
151
|
+
for (const file of localExamples) {
|
|
152
|
+
const relativePath = relativePrefix ? `${ relativePrefix }/${ file.filename }` : file.filename;
|
|
153
|
+
|
|
154
|
+
results.push({
|
|
155
|
+
...file,
|
|
156
|
+
relativePath,
|
|
157
|
+
displayName: relativePath,
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
let childDirs = [];
|
|
162
|
+
|
|
163
|
+
try {
|
|
164
|
+
const dirents = await fs.readdir(dirPath, { withFileTypes: true });
|
|
165
|
+
childDirs = dirents
|
|
166
|
+
.filter(dirent => dirent.isDirectory())
|
|
167
|
+
.map(dirent => dirent.name)
|
|
168
|
+
.filter(name => name[0] !== '_' && name[0] !== '.')
|
|
169
|
+
.filter(name => !excludedDirs.has(name));
|
|
170
|
+
} catch (err) {
|
|
171
|
+
return results;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
for (const childDir of childDirs) {
|
|
175
|
+
const childPrefix = relativePrefix ? `${ relativePrefix }/${ childDir }` : childDir;
|
|
176
|
+
const childResults = await collectMineralExampleFiles(path.join(dirPath, childDir), childPrefix);
|
|
177
|
+
results.push(...childResults);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
return results;
|
|
181
|
+
};
|
|
182
|
+
|
|
127
183
|
const sortExampleFiles = (exampleFiles) => {
|
|
128
184
|
return [...exampleFiles].sort((a, b) => {
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
185
|
+
const aKey = a.relativePath || a.displayName;
|
|
186
|
+
const bKey = b.relativePath || b.displayName;
|
|
187
|
+
|
|
188
|
+
if (aKey === '_example.js') return -1;
|
|
189
|
+
if (bKey === '_example.js') return 1;
|
|
190
|
+
|
|
191
|
+
return aKey.localeCompare(bKey);
|
|
132
192
|
});
|
|
133
193
|
};
|
|
134
194
|
|
|
@@ -148,7 +208,68 @@ const normalizeTemplateArg = (templateArg) => {
|
|
|
148
208
|
return `_example.${ templateArg }.js`;
|
|
149
209
|
};
|
|
150
210
|
|
|
151
|
-
const
|
|
211
|
+
const findWorkspaceTemplate = (exampleFiles, templateArg) => {
|
|
212
|
+
if (!templateArg) {
|
|
213
|
+
const defaultTemplate = exampleFiles.find(file => file.relativePath === '_example.js');
|
|
214
|
+
if (defaultTemplate) {
|
|
215
|
+
return defaultTemplate;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
if (exampleFiles.length === 0) {
|
|
219
|
+
throw new Error('No mineral example templates found');
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
return exampleFiles[0];
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const directMatch = exampleFiles.find(file => file.relativePath === templateArg);
|
|
226
|
+
if (directMatch) {
|
|
227
|
+
return directMatch;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const normalizedFilename = normalizeTemplateArg(templateArg);
|
|
231
|
+
const filenameMatches = exampleFiles.filter(file => file.filename === normalizedFilename);
|
|
232
|
+
|
|
233
|
+
if (templateArg.includes('/')) {
|
|
234
|
+
const [ prefix, suffix ] = templateArg.split('/');
|
|
235
|
+
const normalizedSuffix = normalizeTemplateArg(suffix);
|
|
236
|
+
const prefixedMatch = exampleFiles.find(file => file.relativePath === `${ prefix }/${ normalizedSuffix }`);
|
|
237
|
+
|
|
238
|
+
if (prefixedMatch) {
|
|
239
|
+
return prefixedMatch;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
if (filenameMatches.length === 1) {
|
|
244
|
+
return filenameMatches[0];
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const suffixMatches = exampleFiles.filter(file => file.relativePath.endsWith(`/${ normalizedFilename }`));
|
|
248
|
+
|
|
249
|
+
if (suffixMatches.length === 1) {
|
|
250
|
+
return suffixMatches[0];
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
if (suffixMatches.length > 1) {
|
|
254
|
+
throw new Error(
|
|
255
|
+
`Ambiguous template "${ templateArg }". Use one of: ${ suffixMatches.map(file => file.relativePath).join(', ') }`,
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
throw new Error(`Template not found: ${ templateArg }`);
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
const resolveTemplateFromArg = async ({
|
|
263
|
+
exampleFiles,
|
|
264
|
+
templateArg,
|
|
265
|
+
dir,
|
|
266
|
+
inMineral,
|
|
267
|
+
}) => {
|
|
268
|
+
if (!inMineral) {
|
|
269
|
+
const selectedTemplate = findWorkspaceTemplate(exampleFiles, templateArg);
|
|
270
|
+
return selectedTemplate.fullPath;
|
|
271
|
+
}
|
|
272
|
+
|
|
152
273
|
if (!templateArg) {
|
|
153
274
|
const defaultInDir = exampleFiles.find(file => file.displayName === '_example.js');
|
|
154
275
|
if (defaultInDir) {
|
|
@@ -184,13 +305,51 @@ const scriptFileContents = async (name, selectedTemplate) => {
|
|
|
184
305
|
return exampleFileContents.replace(/FUNC/g, name);
|
|
185
306
|
};
|
|
186
307
|
|
|
187
|
-
const getDirs = async () => {
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
308
|
+
const getDirs = async (targetApiDirectory) => {
|
|
309
|
+
try {
|
|
310
|
+
const dirents = await fs.readdir(targetApiDirectory, { withFileTypes: true });
|
|
311
|
+
return dirents
|
|
312
|
+
.filter(dirent => dirent.isDirectory())
|
|
313
|
+
.map(dirent => dirent.name)
|
|
314
|
+
.filter(name => name[0] !== '_' && name[0] !== '.')
|
|
315
|
+
.filter(name => !excludedDirs.has(name));
|
|
316
|
+
} catch (err) {
|
|
317
|
+
if (err.code === 'ENOENT') {
|
|
318
|
+
return [];
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
throw err;
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
|
|
325
|
+
const normalizeDirArg = (dirArg) => {
|
|
326
|
+
if (!dirArg || dirArg === '.' || dirArg === 'api') {
|
|
327
|
+
return '';
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
return dirArg;
|
|
331
|
+
};
|
|
332
|
+
|
|
333
|
+
const resolveDirArg = ({ dirArg, dirs, inMineral, name }) => {
|
|
334
|
+
const normalizedDir = normalizeDirArg(dirArg);
|
|
335
|
+
|
|
336
|
+
if (dirs.includes(normalizedDir)) {
|
|
337
|
+
return normalizedDir;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
if (!inMineral && dirs.length === 0 && normalizedDir === '') {
|
|
341
|
+
return '';
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
if (!inMineral && !dirArg && name) {
|
|
345
|
+
return '';
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
if (inMineral && !dirArg) {
|
|
349
|
+
return null;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
return normalizedDir;
|
|
194
353
|
};
|
|
195
354
|
|
|
196
355
|
const buildFuncName = (dir, name) => {
|
|
@@ -201,6 +360,11 @@ const buildFuncName = (dir, name) => {
|
|
|
201
360
|
};
|
|
202
361
|
|
|
203
362
|
const selectDirInteractive = async (dirs) => {
|
|
363
|
+
if (dirs.length === 0) {
|
|
364
|
+
console.log('\nCreating in api/');
|
|
365
|
+
return '';
|
|
366
|
+
}
|
|
367
|
+
|
|
204
368
|
const dirIndex = await askQuestion(`Where does your new function live? \n${
|
|
205
369
|
dirs.map((dir, index) => {
|
|
206
370
|
return `[${ index + 1 }] ${ dir }`;
|
|
@@ -216,33 +380,54 @@ const selectDirInteractive = async (dirs) => {
|
|
|
216
380
|
return dir;
|
|
217
381
|
};
|
|
218
382
|
|
|
219
|
-
const
|
|
383
|
+
const getExampleFilesForContext = async ({ context, dir }) => {
|
|
384
|
+
if (context.inMineral) {
|
|
385
|
+
return sortExampleFiles(await findExampleFiles(path.join(context.apiDirectory, dir)));
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
return sortExampleFiles(await collectMineralExampleFiles(context.mineralApiDirectory));
|
|
389
|
+
};
|
|
390
|
+
|
|
391
|
+
const formatTemplateLabel = (file, { inMineral }) => {
|
|
392
|
+
if (inMineral) {
|
|
393
|
+
return file.displayName;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
return file.relativePath;
|
|
397
|
+
};
|
|
398
|
+
|
|
399
|
+
const selectTemplateInteractive = async ({ exampleFiles, dir, inMineral }) => {
|
|
220
400
|
if (exampleFiles.length === 0) {
|
|
221
401
|
await fs.access(rootExampleJsPath);
|
|
222
|
-
console.log('\nUsing template:
|
|
402
|
+
console.log('\nUsing template: _example.js');
|
|
223
403
|
return rootExampleJsPath;
|
|
224
404
|
}
|
|
225
405
|
|
|
226
406
|
if (exampleFiles.length === 1) {
|
|
227
|
-
console.log(`\nUsing template: ${ exampleFiles[0]
|
|
407
|
+
console.log(`\nUsing template: ${ formatTemplateLabel(exampleFiles[0], { inMineral }) }`);
|
|
228
408
|
return exampleFiles[0].fullPath;
|
|
229
409
|
}
|
|
230
410
|
|
|
231
|
-
|
|
411
|
+
const templateScope = inMineral ? `in api/${ dir }` : 'from mineral';
|
|
412
|
+
console.log(`\nFound ${ exampleFiles.length } template(s) ${ templateScope }:`);
|
|
413
|
+
|
|
232
414
|
const templateIndex = await askQuestion(`Which template would you like to use? (press enter for _example.js) \n${
|
|
233
415
|
exampleFiles.map((file, index) => {
|
|
234
|
-
return `[${ index + 1 }] ${ file
|
|
416
|
+
return `[${ index + 1 }] ${ formatTemplateLabel(file, { inMineral }) }`;
|
|
235
417
|
}).join('\n')
|
|
236
418
|
}\n`);
|
|
237
419
|
|
|
238
420
|
if (!templateIndex || templateIndex.trim() === '') {
|
|
239
|
-
const defaultFile = exampleFiles.find(file =>
|
|
421
|
+
const defaultFile = exampleFiles.find(file => (
|
|
422
|
+
file.relativePath === '_example.js' || file.displayName === '_example.js'
|
|
423
|
+
));
|
|
424
|
+
|
|
240
425
|
if (defaultFile) {
|
|
241
426
|
return defaultFile.fullPath;
|
|
242
427
|
}
|
|
243
428
|
|
|
244
429
|
await fs.access(rootExampleJsPath);
|
|
245
|
-
console.log('\nUsing template:
|
|
430
|
+
console.log('\nUsing template: _example.js');
|
|
246
431
|
return rootExampleJsPath;
|
|
247
432
|
}
|
|
248
433
|
|
|
@@ -266,6 +451,7 @@ const selectNameInteractive = async (dir) => {
|
|
|
266
451
|
};
|
|
267
452
|
|
|
268
453
|
const writeNewFunction = async ({
|
|
454
|
+
apiDirectory,
|
|
269
455
|
dir,
|
|
270
456
|
name,
|
|
271
457
|
selectedTemplate,
|
|
@@ -283,6 +469,8 @@ const writeNewFunction = async ({
|
|
|
283
469
|
}
|
|
284
470
|
}
|
|
285
471
|
|
|
472
|
+
await fs.mkdir(path.dirname(outputPath), { recursive: true });
|
|
473
|
+
|
|
286
474
|
const script = await scriptFileContents(funcName, selectedTemplate);
|
|
287
475
|
await fs.writeFile(outputPath, script);
|
|
288
476
|
|
|
@@ -296,38 +484,55 @@ const writeNewFunction = async ({
|
|
|
296
484
|
};
|
|
297
485
|
|
|
298
486
|
const createNewFunction = async () => {
|
|
487
|
+
const context = getContext();
|
|
299
488
|
const cliArgs = parseCliArgs(process.argv.slice(2));
|
|
300
489
|
|
|
301
490
|
if (cliArgs.help) {
|
|
302
|
-
printHelp();
|
|
491
|
+
printHelp(context);
|
|
303
492
|
return;
|
|
304
493
|
}
|
|
305
494
|
|
|
306
|
-
const dirs = await getDirs();
|
|
495
|
+
const dirs = await getDirs(context.apiDirectory);
|
|
307
496
|
const nonInteractive = Boolean(cliArgs.dir || cliArgs.name);
|
|
308
497
|
|
|
309
498
|
if (nonInteractive) {
|
|
310
|
-
if (!cliArgs.
|
|
311
|
-
console.error('Non-interactive mode requires
|
|
312
|
-
printHelp();
|
|
499
|
+
if (!cliArgs.name) {
|
|
500
|
+
console.error('Non-interactive mode requires --name.');
|
|
501
|
+
printHelp(context);
|
|
313
502
|
process.exitCode = 1;
|
|
314
503
|
return;
|
|
315
504
|
}
|
|
316
505
|
|
|
317
|
-
|
|
318
|
-
|
|
506
|
+
const dir = resolveDirArg({
|
|
507
|
+
dirArg: cliArgs.dir,
|
|
508
|
+
dirs,
|
|
509
|
+
inMineral: context.inMineral,
|
|
510
|
+
name: cliArgs.name,
|
|
511
|
+
});
|
|
512
|
+
|
|
513
|
+
if (dir === null || (!dirs.includes(dir) && !(dir === '' && dirs.length === 0 && !context.inMineral))) {
|
|
514
|
+
const availableDirs = dirs.length ? dirs.join(', ') : 'api/ (flat)';
|
|
515
|
+
console.error(`Invalid --dir "${ cliArgs.dir }". Available: ${ availableDirs }`);
|
|
319
516
|
process.exitCode = 1;
|
|
320
517
|
return;
|
|
321
518
|
}
|
|
322
519
|
|
|
323
|
-
const exampleFiles =
|
|
520
|
+
const exampleFiles = await getExampleFilesForContext({ context, dir });
|
|
324
521
|
|
|
325
522
|
try {
|
|
326
|
-
const selectedTemplate = await resolveTemplateFromArg(
|
|
327
|
-
|
|
523
|
+
const selectedTemplate = await resolveTemplateFromArg({
|
|
524
|
+
exampleFiles,
|
|
525
|
+
templateArg: cliArgs.template,
|
|
526
|
+
dir,
|
|
527
|
+
inMineral: context.inMineral,
|
|
528
|
+
});
|
|
529
|
+
|
|
530
|
+
const templateLabel = path.relative(mineralRoot, selectedTemplate);
|
|
531
|
+
console.log(`Using template: ${ templateLabel }`);
|
|
328
532
|
|
|
329
533
|
await writeNewFunction({
|
|
330
|
-
|
|
534
|
+
apiDirectory: context.apiDirectory,
|
|
535
|
+
dir,
|
|
331
536
|
name: cliArgs.name,
|
|
332
537
|
selectedTemplate,
|
|
333
538
|
shouldAutoCommit: process.env.AUTO_COMMIT_STUBS === 'true' || cliArgs.commit,
|
|
@@ -342,11 +547,16 @@ const createNewFunction = async () => {
|
|
|
342
547
|
|
|
343
548
|
try {
|
|
344
549
|
const dir = await selectDirInteractive(dirs);
|
|
345
|
-
const exampleFiles =
|
|
346
|
-
const selectedTemplate = await selectTemplateInteractive(
|
|
550
|
+
const exampleFiles = await getExampleFilesForContext({ context, dir });
|
|
551
|
+
const selectedTemplate = await selectTemplateInteractive({
|
|
552
|
+
exampleFiles,
|
|
553
|
+
dir,
|
|
554
|
+
inMineral: context.inMineral,
|
|
555
|
+
});
|
|
347
556
|
const name = await selectNameInteractive(dir);
|
|
348
557
|
|
|
349
558
|
await writeNewFunction({
|
|
559
|
+
apiDirectory: context.apiDirectory,
|
|
350
560
|
dir,
|
|
351
561
|
name,
|
|
352
562
|
selectedTemplate,
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// https://shopify.dev/docs/apps/build/authentication-authorization/session-tokens/set-up-session-tokens
|
|
2
|
+
|
|
3
|
+
const crypto = require('crypto');
|
|
4
|
+
const { credsFromPayload, ArgsWarden } = require('../utils');
|
|
5
|
+
const { credsValidator } = require('../validators');
|
|
6
|
+
|
|
7
|
+
const sessionTokenValidator = (sessionToken) => {
|
|
8
|
+
return typeof sessionToken === 'string' && Boolean(sessionToken.trim());
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
const argsWarden = new ArgsWarden([
|
|
12
|
+
['credsPayload', credsValidator],
|
|
13
|
+
['sessionToken', sessionTokenValidator],
|
|
14
|
+
]);
|
|
15
|
+
|
|
16
|
+
const base64UrlDecodeJson = (input) => {
|
|
17
|
+
const base64 = input.replace(/-/g, '+').replace(/_/g, '/');
|
|
18
|
+
const padding = '='.repeat((4 - base64.length % 4) % 4);
|
|
19
|
+
|
|
20
|
+
return JSON.parse(Buffer.from(`${ base64 }${ padding }`, 'base64').toString('utf8'));
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const normalizeSessionToken = (sessionToken) => {
|
|
24
|
+
const trimmedToken = sessionToken.trim();
|
|
25
|
+
|
|
26
|
+
if (trimmedToken.toLowerCase().startsWith('bearer ')) {
|
|
27
|
+
return trimmedToken.slice(7).trim();
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return trimmedToken;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
const verifySessionTokenSignature = (token, apiSecret) => {
|
|
34
|
+
const [encodedHeader, encodedPayload, signature] = token.split('.');
|
|
35
|
+
|
|
36
|
+
if (!encodedHeader || !encodedPayload || !signature) {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const message = `${ encodedHeader }.${ encodedPayload }`;
|
|
41
|
+
const computedSignature = crypto
|
|
42
|
+
.createHmac('sha256', apiSecret)
|
|
43
|
+
.update(message)
|
|
44
|
+
.digest('base64url');
|
|
45
|
+
|
|
46
|
+
return computedSignature === signature;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const validateSessionTokenClaims = (
|
|
50
|
+
decoded,
|
|
51
|
+
{
|
|
52
|
+
checkAudience = true,
|
|
53
|
+
clientId,
|
|
54
|
+
} = {},
|
|
55
|
+
) => {
|
|
56
|
+
const {
|
|
57
|
+
iss,
|
|
58
|
+
dest,
|
|
59
|
+
aud,
|
|
60
|
+
exp,
|
|
61
|
+
nbf,
|
|
62
|
+
} = decoded;
|
|
63
|
+
|
|
64
|
+
const currentTime = Math.floor(Date.now() / 1000);
|
|
65
|
+
const expValid = exp > currentTime;
|
|
66
|
+
const nbfValid = nbf <= currentTime;
|
|
67
|
+
const domainsValid = dest?.includes('myshopify.com') && iss?.includes('myshopify.com');
|
|
68
|
+
const audValid = !checkAudience || aud === clientId;
|
|
69
|
+
|
|
70
|
+
return expValid && nbfValid && domainsValid && audValid;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const decodeSessionTokenPayload = (token) => {
|
|
74
|
+
const encodedPayload = token.split('.')[1];
|
|
75
|
+
|
|
76
|
+
if (!encodedPayload) {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
try {
|
|
81
|
+
return base64UrlDecodeJson(encodedPayload);
|
|
82
|
+
} catch (error) {
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const shopifyDecodeSessionToken = async (
|
|
88
|
+
credsPayload,
|
|
89
|
+
sessionToken,
|
|
90
|
+
{
|
|
91
|
+
checkAudience = true,
|
|
92
|
+
} = {},
|
|
93
|
+
) => {
|
|
94
|
+
|
|
95
|
+
const rejectResponse = await argsWarden.responseIfRejectingArgs({
|
|
96
|
+
credsPayload,
|
|
97
|
+
sessionToken,
|
|
98
|
+
});
|
|
99
|
+
if (rejectResponse) {
|
|
100
|
+
return rejectResponse;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const creds = await credsFromPayload(credsPayload);
|
|
104
|
+
const {
|
|
105
|
+
API_SECRET,
|
|
106
|
+
CLIENT_ID,
|
|
107
|
+
} = creds;
|
|
108
|
+
|
|
109
|
+
if (!API_SECRET || !CLIENT_ID) {
|
|
110
|
+
return {
|
|
111
|
+
ok: false,
|
|
112
|
+
error: {
|
|
113
|
+
code: 'INVALID_CREDS',
|
|
114
|
+
message: 'API_SECRET and CLIENT_ID are required.',
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const token = normalizeSessionToken(sessionToken);
|
|
120
|
+
const decoded = decodeSessionTokenPayload(token);
|
|
121
|
+
|
|
122
|
+
if (!decoded) {
|
|
123
|
+
return {
|
|
124
|
+
ok: false,
|
|
125
|
+
error: {
|
|
126
|
+
code: 'INVALID_SESSION_TOKEN',
|
|
127
|
+
message: 'Session token could not be decoded.',
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (!verifySessionTokenSignature(token, API_SECRET)) {
|
|
133
|
+
return {
|
|
134
|
+
ok: false,
|
|
135
|
+
error: {
|
|
136
|
+
code: 'INVALID_SESSION_TOKEN',
|
|
137
|
+
message: 'Session token signature is invalid.',
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
if (!validateSessionTokenClaims(decoded, {
|
|
143
|
+
checkAudience,
|
|
144
|
+
clientId: CLIENT_ID,
|
|
145
|
+
})) {
|
|
146
|
+
return {
|
|
147
|
+
ok: false,
|
|
148
|
+
error: {
|
|
149
|
+
code: 'INVALID_SESSION_TOKEN',
|
|
150
|
+
message: 'Session token claims are invalid.',
|
|
151
|
+
details: decoded,
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return {
|
|
157
|
+
ok: true,
|
|
158
|
+
data: decoded,
|
|
159
|
+
};
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
const funcApiConfig = {
|
|
163
|
+
argsWarden,
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
module.exports = {
|
|
167
|
+
shopifyDecodeSessionToken,
|
|
168
|
+
funcApiConfig,
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
/*
|
|
172
|
+
curl -X POST "http://localhost:8000/shopifyDecodeSessionToken" \
|
|
173
|
+
-H "Content-Type: application/json" \
|
|
174
|
+
-d '{
|
|
175
|
+
"credsPayload": { "credsPath": "tender.prod" },
|
|
176
|
+
"sessionToken": "<jwt>"
|
|
177
|
+
}'
|
|
178
|
+
*/
|
|
179
|
+
|
|
180
|
+
/*
|
|
181
|
+
Legacy usage:
|
|
182
|
+
const whichApp = req.headers['x-wf-app'];
|
|
183
|
+
|
|
184
|
+
const sessionToken = req?.headers?.authorization?.split(' ')?.pop();
|
|
185
|
+
if (!sessionToken) {
|
|
186
|
+
return respond(res, 401, {
|
|
187
|
+
error: 'Unauthorized: No session token',
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const sessionTokenData = shopifyDecodeSessionToken(sessionToken, {
|
|
192
|
+
...whichApp && { credsPath: whichApp },
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
const {
|
|
196
|
+
dest,
|
|
197
|
+
sub: customerGid,
|
|
198
|
+
} = sessionTokenData;
|
|
199
|
+
|
|
200
|
+
const config = domainToConfig(dest);
|
|
201
|
+
if (!config) {
|
|
202
|
+
return respond(res, 401, {
|
|
203
|
+
error: 'No config found for domain',
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
*/
|