gipity 1.1.40 → 1.1.42
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/dist/approval-verify.js +113 -0
- package/dist/commands/approval.js +85 -2
- package/dist/commands/deploy.js +13 -6
- package/dist/commands/key.js +5 -0
- package/dist/commands/load.js +44 -2
- package/dist/commands/notify.js +105 -12
- package/dist/commands/save.js +19 -4
- package/dist/commands/status.js +15 -1
- package/dist/index.js +632 -343
- package/dist/knowledge.js +3 -2
- package/package.json +2 -2
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Offline verification of a Gipity passkey approval: exactly the checks a
|
|
3
|
+
* device outside Gipity makes before it runs an approved action. Nothing here
|
|
4
|
+
* trusts the server: the payload hash and challenge are recomputed locally and
|
|
5
|
+
* the signature is checked against a key the caller pinned at enrollment.
|
|
6
|
+
*
|
|
7
|
+
* Rules (the app-approvals skill documents the same):
|
|
8
|
+
* payloadHash = hex sha256 of the canonical JSON of the payload (RFC 8785:
|
|
9
|
+
* keys sorted, no whitespace, JSON.stringify scalars)
|
|
10
|
+
* challenge = sha256("gipity-approval:v1|" + id + "|" + payloadHash + "|" + expiresAt)
|
|
11
|
+
* clientDataJSON.type == "webauthn.get", .challenge == base64url(challenge), .origin == expected origin
|
|
12
|
+
* authenticatorData: rpIdHash == sha256(rpId), flags UP (0x01) and UV (0x04) set
|
|
13
|
+
* signature over authenticatorData || sha256(clientDataJSON), verified with the pinned key
|
|
14
|
+
* expiresAt in the future
|
|
15
|
+
*/
|
|
16
|
+
import { createHash, createPublicKey, verify } from 'node:crypto';
|
|
17
|
+
const CHALLENGE_PREFIX = 'gipity-approval:v1|';
|
|
18
|
+
/** RFC 8785 canonical JSON. Throws on values JSON can't represent exactly. */
|
|
19
|
+
export function canonicalJson(value) {
|
|
20
|
+
if (value === null)
|
|
21
|
+
return 'null';
|
|
22
|
+
switch (typeof value) {
|
|
23
|
+
case 'boolean':
|
|
24
|
+
case 'string':
|
|
25
|
+
return JSON.stringify(value);
|
|
26
|
+
case 'number':
|
|
27
|
+
if (!Number.isFinite(value))
|
|
28
|
+
throw new Error('payload contains a non-finite number');
|
|
29
|
+
return JSON.stringify(value);
|
|
30
|
+
case 'object': {
|
|
31
|
+
if (Array.isArray(value))
|
|
32
|
+
return `[${value.map(canonicalJson).join(',')}]`;
|
|
33
|
+
const obj = value;
|
|
34
|
+
return `{${Object.keys(obj).sort().map((k) => {
|
|
35
|
+
if (obj[k] === undefined)
|
|
36
|
+
throw new Error(`payload field '${k}' is undefined`);
|
|
37
|
+
return `${JSON.stringify(k)}:${canonicalJson(obj[k])}`;
|
|
38
|
+
}).join(',')}}`;
|
|
39
|
+
}
|
|
40
|
+
default:
|
|
41
|
+
throw new Error(`payload contains a value JSON can't represent (${typeof value})`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const sha256 = (data) => createHash('sha256').update(data).digest();
|
|
45
|
+
export function payloadHash(payload) {
|
|
46
|
+
return sha256(canonicalJson(payload)).toString('hex');
|
|
47
|
+
}
|
|
48
|
+
export function approvalChallenge(id, hash, expiresAt) {
|
|
49
|
+
return sha256(`${CHALLENGE_PREFIX}${id}|${hash}|${expiresAt}`).toString('base64url');
|
|
50
|
+
}
|
|
51
|
+
function sameKey(a, b) {
|
|
52
|
+
if (a.kty !== b.kty)
|
|
53
|
+
return false;
|
|
54
|
+
if (a.kty === 'EC')
|
|
55
|
+
return a.crv === b.crv && a.x === b.x && a.y === b.y;
|
|
56
|
+
if (a.kty === 'OKP')
|
|
57
|
+
return a.crv === b.crv && a.x === b.x;
|
|
58
|
+
if (a.kty === 'RSA')
|
|
59
|
+
return a.n === b.n && a.e === b.e;
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
function verifySignature(jwk, data, signature) {
|
|
63
|
+
const key = createPublicKey({ key: { kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y, n: jwk.n, e: jwk.e }, format: 'jwk' });
|
|
64
|
+
// ES256 and RS256 hash with SHA-256 (ECDSA signatures are DER, as WebAuthn
|
|
65
|
+
// sends them); Ed25519 signs the message itself.
|
|
66
|
+
return verify(jwk.kty === 'OKP' ? null : 'sha256', data, key, signature);
|
|
67
|
+
}
|
|
68
|
+
export function verifyApproval(approval, opts) {
|
|
69
|
+
const checks = [];
|
|
70
|
+
const add = (check, ok, detail) => checks.push(detail ? { check, ok, detail } : { check, ok });
|
|
71
|
+
const proof = approval.proof;
|
|
72
|
+
if (!proof) {
|
|
73
|
+
add('proof present', false, `approval is ${approval.status}; there is no passkey proof`);
|
|
74
|
+
return { ok: false, pinned: !!opts.pinnedJwk, checks };
|
|
75
|
+
}
|
|
76
|
+
const expectedRpId = new URL(opts.expectedOrigin).hostname;
|
|
77
|
+
const hash = payloadHash(opts.payload);
|
|
78
|
+
add('payload hash matches', hash === approval.payloadHash, hash === approval.payloadHash ? undefined : `local ${hash}`);
|
|
79
|
+
const challenge = approvalChallenge(approval.id, hash, approval.expiresAt);
|
|
80
|
+
let clientData = {};
|
|
81
|
+
const clientDataBytes = Buffer.from(proof.clientDataJSON, 'base64url');
|
|
82
|
+
try {
|
|
83
|
+
clientData = JSON.parse(clientDataBytes.toString('utf8'));
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
add('clientDataJSON parses', false);
|
|
87
|
+
}
|
|
88
|
+
add('clientData type is webauthn.get', clientData.type === 'webauthn.get');
|
|
89
|
+
add('clientData challenge matches', clientData.challenge === challenge);
|
|
90
|
+
add('clientData origin matches', clientData.origin === opts.expectedOrigin, clientData.origin === opts.expectedOrigin ? undefined : `got ${String(clientData.origin)}`);
|
|
91
|
+
const authData = Buffer.from(proof.authenticatorData, 'base64url');
|
|
92
|
+
const rpIdOk = authData.length >= 37 && authData.subarray(0, 32).equals(sha256(expectedRpId));
|
|
93
|
+
add('rpIdHash matches', rpIdOk);
|
|
94
|
+
const flags = authData.length >= 37 ? authData[32] : 0;
|
|
95
|
+
add('user present (UP)', (flags & 0x01) !== 0);
|
|
96
|
+
add('user verified (UV)', (flags & 0x04) !== 0);
|
|
97
|
+
const key = opts.pinnedJwk ?? proof.publicKeyJwk;
|
|
98
|
+
if (opts.pinnedJwk)
|
|
99
|
+
add('proof key is the pinned key', sameKey(opts.pinnedJwk, proof.publicKeyJwk));
|
|
100
|
+
let sigOk = false;
|
|
101
|
+
try {
|
|
102
|
+
sigOk = verifySignature(key, Buffer.concat([authData, sha256(clientDataBytes)]), Buffer.from(proof.signature, 'base64url'));
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
sigOk = false;
|
|
106
|
+
}
|
|
107
|
+
add('signature verifies', sigOk);
|
|
108
|
+
const expiresMs = Date.parse(approval.expiresAt);
|
|
109
|
+
const notExpired = Number.isFinite(expiresMs) && expiresMs > (opts.now ?? Date.now());
|
|
110
|
+
add('not expired', notExpired, notExpired ? undefined : `expired at ${approval.expiresAt}`);
|
|
111
|
+
return { ok: checks.every((c) => c.ok), pinned: !!opts.pinnedJwk, checks };
|
|
112
|
+
}
|
|
113
|
+
//# sourceMappingURL=approval-verify.js.map
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
1
2
|
import { Command, Option } from 'commander';
|
|
2
|
-
import { get, post } from '../api.js';
|
|
3
|
+
import { get, post, del, getBaseUrl } from '../api.js';
|
|
3
4
|
import { muted, success } from '../colors.js';
|
|
5
|
+
import { verifyApproval } from '../approval-verify.js';
|
|
4
6
|
import { run, printList, printResult } from '../helpers/index.js';
|
|
5
7
|
function timeAgo(dateStr) {
|
|
6
8
|
const diffMs = Date.now() - new Date(dateStr).getTime();
|
|
@@ -29,7 +31,7 @@ approvalCommand
|
|
|
29
31
|
.option('--json', 'Output as JSON')
|
|
30
32
|
.action((opts) => run('List', async () => {
|
|
31
33
|
const res = await get(`/approvals?status=${encodeURIComponent(opts.status)}`);
|
|
32
|
-
printList(res.data, opts, 'No approvals.', a => `${a.guid} ${a.title} ${muted(`[${a.status}] ${timeAgo(a.created_at)}`)}`);
|
|
34
|
+
printList(res.data, opts, 'No approvals.', a => `${a.guid} ${a.title} ${muted(`[${a.status}${a.kind === 'passkey' ? ', passkey' : ''}] ${timeAgo(a.created_at)}`)}`);
|
|
33
35
|
}));
|
|
34
36
|
approvalCommand
|
|
35
37
|
.command('create <title...>')
|
|
@@ -124,4 +126,85 @@ approvalCommand
|
|
|
124
126
|
await post(`/approvals/${guid}/cancel`, {});
|
|
125
127
|
printResult(success(`Cancelled ${guid}.`), opts, { guid, cancelled: true });
|
|
126
128
|
}));
|
|
129
|
+
function requireGuid(guid) {
|
|
130
|
+
if (!guid.startsWith('ap_'))
|
|
131
|
+
throw new Error('Expected approval guid like ap_xxxxxxxx');
|
|
132
|
+
}
|
|
133
|
+
approvalCommand
|
|
134
|
+
.command('show <guid>')
|
|
135
|
+
.description('Show one approval (for a passkey approval: status, payload hash, expiry and whether it carries a signed proof)')
|
|
136
|
+
.option('--json', 'Output as JSON')
|
|
137
|
+
.action((guid, opts) => run('Show', async () => {
|
|
138
|
+
requireGuid(guid);
|
|
139
|
+
const { data } = await get(`/approvals/${guid}`);
|
|
140
|
+
const lines = [`${data.guid} ${data.title}`];
|
|
141
|
+
if (data.description)
|
|
142
|
+
lines.push(muted(data.description));
|
|
143
|
+
if (data.passkey) {
|
|
144
|
+
const p = data.passkey;
|
|
145
|
+
lines.push(`Status: ${p.status} (passkey)`, `Approver: ${p.approver}`, `Payload hash: ${p.payloadHash}`, `Expires: ${p.expiresAt}`, `Resolved: ${p.resolvedAt ?? '-'}`, `Consumed: ${p.consumedAt ?? '-'}`, `Proof: ${p.proof ? `signed by passkey ${p.proof.credentialId}` : 'none'}`);
|
|
146
|
+
}
|
|
147
|
+
else {
|
|
148
|
+
lines.push(`Status: ${data.status}`);
|
|
149
|
+
}
|
|
150
|
+
printResult(lines.join('\n'), opts, data);
|
|
151
|
+
}));
|
|
152
|
+
approvalCommand
|
|
153
|
+
.command('passkeys')
|
|
154
|
+
.description('List the passkeys you approve with (add them in the browser at the printed link)')
|
|
155
|
+
.option('--remove <id>', 'Remove one of your passkeys by id')
|
|
156
|
+
.option('--json', 'Output as JSON')
|
|
157
|
+
.action((opts) => run('Passkeys', async () => {
|
|
158
|
+
if (opts.remove) {
|
|
159
|
+
await del(`/approvals/passkeys/credentials/${encodeURIComponent(opts.remove)}`);
|
|
160
|
+
printResult(success(`Removed ${opts.remove}.`), opts, { id: opts.remove, removed: true });
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
const { data } = await get('/approvals/passkeys/credentials');
|
|
164
|
+
const manageUrl = `${getBaseUrl()}/approvals/passkeys`;
|
|
165
|
+
if (opts.json) {
|
|
166
|
+
console.log(JSON.stringify({ passkeys: data, manageUrl }));
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
console.log(data.length
|
|
170
|
+
? data.map(k => `${k.id} ${k.label ?? 'Passkey'} ${muted(`added ${k.createdAt.slice(0, 10)}${k.lastUsedAt ? `, last used ${k.lastUsedAt.slice(0, 10)}` : ''}`)}`).join('\n')
|
|
171
|
+
: 'No passkeys yet.');
|
|
172
|
+
console.log(muted(`Add or remove passkeys in the browser: ${manageUrl}`));
|
|
173
|
+
}));
|
|
174
|
+
approvalCommand
|
|
175
|
+
.command('verify <guid>')
|
|
176
|
+
.description('Verify a passkey approval offline, as a device does: recompute the payload hash and challenge and check the passkey signature')
|
|
177
|
+
.requiredOption('--payload <file>', 'JSON file with the exact payload the approval is for')
|
|
178
|
+
.option('--key <file>', "The approver's public key (JWK JSON) pinned at enrollment; without it the proof's own key is used and the result says so")
|
|
179
|
+
.option('--origin <url>', 'Relying-party origin the passkey signed for (default: the API base)')
|
|
180
|
+
.option('--json', 'Output as JSON')
|
|
181
|
+
.action((guid, opts) => run('Verify', async () => {
|
|
182
|
+
requireGuid(guid);
|
|
183
|
+
const payload = JSON.parse(readFileSync(opts.payload, 'utf8'));
|
|
184
|
+
const pinnedJwk = opts.key ? JSON.parse(readFileSync(opts.key, 'utf8')) : undefined;
|
|
185
|
+
const { data } = await get(`/approvals/${guid}`);
|
|
186
|
+
if (!data.passkey)
|
|
187
|
+
throw new Error(`${guid} is not a passkey approval`);
|
|
188
|
+
const expectedOrigin = new URL(opts.origin ?? getBaseUrl()).origin;
|
|
189
|
+
const result = verifyApproval(data.passkey, { payload, pinnedJwk, expectedOrigin });
|
|
190
|
+
if (opts.json) {
|
|
191
|
+
console.log(JSON.stringify({ id: guid, status: data.passkey.status, ...result }));
|
|
192
|
+
}
|
|
193
|
+
else {
|
|
194
|
+
for (const c of result.checks)
|
|
195
|
+
console.log(`${c.ok ? 'ok ' : 'FAIL'} ${c.check}${c.detail ? muted(` (${c.detail})`) : ''}`);
|
|
196
|
+
if (!result.pinned)
|
|
197
|
+
console.log(muted('Key not pinned: checked against the key in the proof. Pass --key with the approver key you pinned.'));
|
|
198
|
+
if (result.ok && data.passkey.status !== 'approved')
|
|
199
|
+
console.log(muted(`Signature is valid, but the approval is ${data.passkey.status}.`));
|
|
200
|
+
}
|
|
201
|
+
if (!result.ok) {
|
|
202
|
+
// --json already printed the failing checks; exit non-zero without a second JSON line.
|
|
203
|
+
if (opts.json) {
|
|
204
|
+
process.exitCode = 1;
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
throw new Error('verification failed');
|
|
208
|
+
}
|
|
209
|
+
}));
|
|
127
210
|
//# sourceMappingURL=approval.js.map
|
package/dist/commands/deploy.js
CHANGED
|
@@ -50,7 +50,7 @@ export const deployCommand = new Command('deploy')
|
|
|
50
50
|
.option('--yes-destructive', 'Allow pending prod migrations that destroy data (DROP TABLE/COLUMN, TRUNCATE, DELETE without WHERE, column type changes)')
|
|
51
51
|
.option('--plan', 'Show the pending migrations this deploy would run (and where each already ran), without deploying')
|
|
52
52
|
.option('--source-dir <dir>', 'Source directory to deploy from')
|
|
53
|
-
.option('--only <phases>', 'Run only specific phases, comma-separated, matched by gipity.yaml phase name or type: files/static, database/sql, functions, workflows, services, jobs, records, realtime, env, auth_branding, auth')
|
|
53
|
+
.option('--only <phases>', 'Run only specific phases, comma-separated, matched by gipity.yaml phase name or type: files/static, database/sql, functions, workflows, services, jobs, records, realtime, env, auth_branding, auth, access')
|
|
54
54
|
.option('--force', 'Re-run all phases (ignore checksums) and bypass the sync bulk-deletion guard')
|
|
55
55
|
.option('--no-sync', 'Skip sync-up before deploy')
|
|
56
56
|
.option('--optimize', 'Bundle and minify the JS/CSS with Vite (off by default: files upload as-is, so prod serves what you verified). Only bundles <script type="module"> references, and page eval import() of an app module then loads a separate copy')
|
|
@@ -90,7 +90,6 @@ export const deployCommand = new Command('deploy')
|
|
|
90
90
|
? await doDeploy()
|
|
91
91
|
: await withSpinner(env ? `Deploying to ${env}...` : 'Deploying...', doDeploy, { done: null });
|
|
92
92
|
const d = res.data;
|
|
93
|
-
const where = d.env ?? d.target;
|
|
94
93
|
// Deploy + verify in one command: after a successful deploy, run the
|
|
95
94
|
// same inspect pipeline `page inspect` uses against the live URL. An
|
|
96
95
|
// inspect failure is reported but never turns a successful deploy into
|
|
@@ -131,7 +130,7 @@ export const deployCommand = new Command('deploy')
|
|
|
131
130
|
}
|
|
132
131
|
// Format output
|
|
133
132
|
const batchLabel = d.batch ? muted(` (batch ${d.batch})`) : '';
|
|
134
|
-
console.log(brand(bold(`Deploy to ${
|
|
133
|
+
console.log(brand(bold(`Deploy to ${d.env}`)) + batchLabel + (d.created ? muted(' (new environment)') : ''));
|
|
135
134
|
console.log(muted('─'.repeat(40)));
|
|
136
135
|
if (d.phases && d.phases.length > 0) {
|
|
137
136
|
for (const phase of d.phases) {
|
|
@@ -178,12 +177,14 @@ export const deployCommand = new Command('deploy')
|
|
|
178
177
|
process.exit(1);
|
|
179
178
|
}
|
|
180
179
|
else {
|
|
181
|
-
console.log(success(`✓ Deployed to ${
|
|
180
|
+
console.log(success(`✓ Deployed to ${d.env}`) + muted(` (${d.elapsedMs}ms)`));
|
|
182
181
|
// The live URL is the one thing the caller (often an agent) needs next
|
|
183
182
|
// - to open it, inspect it, or report it. Always surface it so nobody
|
|
184
183
|
// has to reconstruct the URL convention or guess a subdomain.
|
|
185
184
|
if (d.url)
|
|
186
185
|
console.log(`${muted('Live:')} ${brand(d.url)}`);
|
|
186
|
+
if (d.pageAccess && d.pageAccess !== 'public')
|
|
187
|
+
console.log(`${muted('Pages:')} ${pageAccessLabel(d.pageAccess)}`);
|
|
187
188
|
// Functions are served from the API host, NOT the static Live URL -
|
|
188
189
|
// for an API-only app the endpoint address IS the deliverable, so name
|
|
189
190
|
// it instead of leaving it to be inferred from a template comment.
|
|
@@ -192,9 +193,9 @@ export const deployCommand = new Command('deploy')
|
|
|
192
193
|
// --api-base flag and GIPITY_API_BASE env), not the raw stored
|
|
193
194
|
// config.apiBase - otherwise on any override we'd advertise a host we
|
|
194
195
|
// didn't deploy to and send the caller probing the wrong instance.
|
|
195
|
-
console.log(`${muted('Functions:')} POST ${brand(`${resolveApiBase()}/api/${d.appGuid
|
|
196
|
+
console.log(`${muted('Functions:')} POST ${brand(`${resolveApiBase()}/api/${d.appGuid}/fn/<name>`)}`);
|
|
196
197
|
// Each environment has its own functions at its own address.
|
|
197
|
-
const envFlag = d.env
|
|
198
|
+
const envFlag = d.env !== 'prod' ? ` --env ${d.env}` : '';
|
|
198
199
|
console.log(muted(` (names: gipity fn list${envFlag}; verify the public path: gipity fn call <name>${envFlag} --anon)`));
|
|
199
200
|
}
|
|
200
201
|
for (const hint of d.hints ?? [])
|
|
@@ -202,4 +203,10 @@ export const deployCommand = new Command('deploy')
|
|
|
202
203
|
await inspectAfter();
|
|
203
204
|
}
|
|
204
205
|
}));
|
|
206
|
+
/** How a private site's pages are gated, for deploy and status output. */
|
|
207
|
+
export function pageAccessLabel(mode) {
|
|
208
|
+
return mode === 'members'
|
|
209
|
+
? 'private: only you and project members (Gipity sign-in)'
|
|
210
|
+
: "private: only the app's signed-in users";
|
|
211
|
+
}
|
|
205
212
|
//# sourceMappingURL=deploy.js.map
|
package/dist/commands/key.js
CHANGED
|
@@ -68,6 +68,8 @@ export function scopesFromFlags(opts) {
|
|
|
68
68
|
}
|
|
69
69
|
if (opts.files !== undefined)
|
|
70
70
|
scopes.files = opts.files;
|
|
71
|
+
if (opts.approvals !== undefined)
|
|
72
|
+
scopes.approvals = opts.approvals;
|
|
71
73
|
if (opts.ip !== undefined) {
|
|
72
74
|
const ips = splitList(opts.ip);
|
|
73
75
|
if (!ips.length)
|
|
@@ -87,6 +89,8 @@ export function describeScopes(scopes) {
|
|
|
87
89
|
parts.push(`tables: ${Object.entries(scopes.tables).map(([t, a]) => `${t}:${a}`).join(',')}`);
|
|
88
90
|
if (scopes.files)
|
|
89
91
|
parts.push(`files: ${scopes.files}`);
|
|
92
|
+
if (scopes.approvals)
|
|
93
|
+
parts.push(`approvals: ${scopes.approvals}`);
|
|
90
94
|
if (scopes.ip)
|
|
91
95
|
parts.push(`ip: ${scopes.ip.join(',')}`);
|
|
92
96
|
return parts.join(' ');
|
|
@@ -104,6 +108,7 @@ keyCommand
|
|
|
104
108
|
.option('--functions <names>', 'Scope: only these functions (comma-separated)')
|
|
105
109
|
.option('--tables <list>', 'Scope: only these Records tables, e.g. commands:write,logs:read')
|
|
106
110
|
.addOption(new Option('--files <access>', 'Scope: app files access').choices(['read', 'write']))
|
|
111
|
+
.addOption(new Option('--approvals <access>', 'Scope: read and consume passkey approvals').choices(['read']))
|
|
107
112
|
.option('--ip <list>', 'Scope: only from these IPs / CIDR ranges (comma-separated)')
|
|
108
113
|
.option(...projectOpt)
|
|
109
114
|
.option('--json', 'Output as JSON')
|
package/dist/commands/load.js
CHANGED
|
@@ -7,6 +7,11 @@
|
|
|
7
7
|
* `--inspect` to peek inside a source - metadata, contents, deploy phases,
|
|
8
8
|
* and each function's permission surface - without creating anything.
|
|
9
9
|
*
|
|
10
|
+
* A bundle saved with `gipity save --with-data` also carries database rows:
|
|
11
|
+
* the server builds the new app's database from the bundle's migrations and
|
|
12
|
+
* loads them, and the summary lists each table's row count (`--inspect` shows
|
|
13
|
+
* the same counts without loading anything).
|
|
14
|
+
*
|
|
10
15
|
* Sources:
|
|
11
16
|
* - a local .gip file (from `gipity save`) - uploaded as raw zip bytes
|
|
12
17
|
* - `github:owner/repo[/sub/path][@ref]` or a github.com URL - resolved
|
|
@@ -88,6 +93,13 @@ function printManifest(m) {
|
|
|
88
93
|
}
|
|
89
94
|
}
|
|
90
95
|
}
|
|
96
|
+
/** One line per table: ` database.table N rows`. */
|
|
97
|
+
function printTableCounts(databases) {
|
|
98
|
+
const rows = databases.flatMap(db => db.tables.map(t => ({ name: `${db.database}.${t.table}`, rows: t.rows })));
|
|
99
|
+
const width = Math.max(0, ...rows.map(r => r.name.length));
|
|
100
|
+
for (const r of rows)
|
|
101
|
+
console.log(` ${r.name.padEnd(width)} ${muted(`${r.rows} row(s)`)}`);
|
|
102
|
+
}
|
|
91
103
|
function printInspect(d, source) {
|
|
92
104
|
if (d.meta) {
|
|
93
105
|
console.log(bold(d.meta.name));
|
|
@@ -104,13 +116,22 @@ function printInspect(d, source) {
|
|
|
104
116
|
console.log('');
|
|
105
117
|
printManifest(d.manifest);
|
|
106
118
|
console.log('');
|
|
119
|
+
if (d.data) {
|
|
120
|
+
const tables = d.data.databases.reduce((n, db) => n + db.tables.length, 0);
|
|
121
|
+
console.log(bold(`Data: ${d.data.rows} row(s) in ${tables} table(s), ${formatBytes(d.data.bytes)}`));
|
|
122
|
+
printTableCounts(d.data.databases);
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
console.log(muted('Data: none (code, migrations and seeds only)'));
|
|
126
|
+
}
|
|
127
|
+
console.log('');
|
|
107
128
|
console.log(muted('Load it with `gipity load ' + source + '` - always creates a NEW project.'));
|
|
108
129
|
}
|
|
109
130
|
export const loadCommand = new Command('load')
|
|
110
131
|
.description('Create a new app from a .gip bundle or a GitHub repo')
|
|
111
132
|
.argument('<source>', 'A .gip file (from `gipity save`), github:owner/repo[/sub/path][@ref], or a github.com URL')
|
|
112
133
|
.option('--name <name>', 'Name for the new project (default: the source\'s saved name)')
|
|
113
|
-
.option('--inspect', 'Peek inside the source - contents, deploy phases, function permissions - without creating anything')
|
|
134
|
+
.option('--inspect', 'Peek inside the source - contents, deploy phases, function permissions, saved data - without creating anything')
|
|
114
135
|
.option('--json', 'Output as JSON')
|
|
115
136
|
.addHelpText('after', '\nLoad always creates a NEW project - it never merges into an existing one.'
|
|
116
137
|
+ '\nGitHub sources need a one-time `gipity github connect` (re-run it to grant more repos).')
|
|
@@ -190,7 +211,10 @@ export const loadCommand = new Command('load')
|
|
|
190
211
|
failed: data.failed,
|
|
191
212
|
partial,
|
|
192
213
|
applied,
|
|
214
|
+
...(data.data ? { data: data.data } : {}),
|
|
193
215
|
}));
|
|
216
|
+
if (data.data && !data.data.loaded)
|
|
217
|
+
process.exitCode = 1;
|
|
194
218
|
return;
|
|
195
219
|
}
|
|
196
220
|
console.log(success(`Created "${project.name}" (${project.slug}) from ${sourceLabel}`));
|
|
@@ -205,7 +229,25 @@ export const loadCommand = new Command('load')
|
|
|
205
229
|
console.warn(warning(` ! ${f.path}: ${f.error}`));
|
|
206
230
|
console.warn(warning('The project was still created and linked; the files above are missing from it.'));
|
|
207
231
|
}
|
|
232
|
+
if (data.data?.loaded) {
|
|
233
|
+
console.log('');
|
|
234
|
+
console.log(success(`Loaded ${data.data.rows} row(s) into the app's database:`));
|
|
235
|
+
printTableCounts(data.data.databases);
|
|
236
|
+
}
|
|
237
|
+
else if (data.data) {
|
|
238
|
+
console.log('');
|
|
239
|
+
console.warn(warning(`The bundle's rows were not loaded: ${data.data.error}`));
|
|
240
|
+
console.warn(warning('The project was still created and linked, with an empty database. Delete it with `gipity project delete` and load again once the problem is fixed.'));
|
|
241
|
+
process.exitCode = 1;
|
|
242
|
+
}
|
|
208
243
|
console.log('');
|
|
209
|
-
|
|
244
|
+
if (data.data?.loaded) {
|
|
245
|
+
// The rows went into prod (where a new app lives); a dev environment starts empty.
|
|
246
|
+
console.log(`${muted('Next:')} cd ${dir} && ${brand('gipity deploy prod')}`);
|
|
247
|
+
console.log(muted('The rows are in the prod database. `gipity env create dev --data` gives you a dev copy with them.'));
|
|
248
|
+
}
|
|
249
|
+
else {
|
|
250
|
+
console.log(`${muted('Next:')} cd ${dir} && ${brand('gipity deploy dev')}`);
|
|
251
|
+
}
|
|
210
252
|
}));
|
|
211
253
|
//# sourceMappingURL=load.js.map
|
package/dist/commands/notify.js
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import { Command } from 'commander';
|
|
2
|
-
import {
|
|
2
|
+
import { readFileSync } from 'fs';
|
|
3
|
+
import { get, post, put, del } from '../api.js';
|
|
3
4
|
import { resolveProjectContext } from '../config.js';
|
|
4
5
|
import { bold, muted, success, warning } from '../colors.js';
|
|
5
6
|
import { run } from '../helpers/index.js';
|
|
6
7
|
export const notifyCommand = new Command('notify')
|
|
7
|
-
.description('
|
|
8
|
-
.addHelpText('after', '\nGipity Notify: send a test notification or
|
|
8
|
+
.description('Push notifications (web and native iOS)')
|
|
9
|
+
.addHelpText('after', '\nGipity Notify: send a test notification, inspect subscriptions, or set up iOS push (notify apns).');
|
|
9
10
|
notifyCommand
|
|
10
11
|
.command('test')
|
|
11
|
-
.description('Send a test push notification to
|
|
12
|
+
.description('Send a test push notification (web and iOS devices) to a user or everyone')
|
|
12
13
|
.option('--to <who>', "Recipient: a user guid, comma-separated guids, or 'all'", 'all')
|
|
13
14
|
.option('--title <text>', 'Notification title', 'Test notification')
|
|
14
15
|
.option('--body <text>', 'Notification body', 'Hello from Gipity Notify 👋')
|
|
@@ -26,15 +27,25 @@ notifyCommand
|
|
|
26
27
|
console.log(JSON.stringify(res.data));
|
|
27
28
|
return;
|
|
28
29
|
}
|
|
29
|
-
const { sent, failed, pruned } = res.data;
|
|
30
|
-
if (sent > 0)
|
|
31
|
-
|
|
32
|
-
|
|
30
|
+
const { sent, failed, pruned, results } = res.data;
|
|
31
|
+
if (sent > 0) {
|
|
32
|
+
const ios = results.filter(r => r.transport === 'apns' && r.status === 'sent').length;
|
|
33
|
+
const web = sent - ios;
|
|
34
|
+
const split = ios > 0 ? ` (${web} web, ${ios} iOS)` : '';
|
|
35
|
+
console.log(success(`✓ Sent to ${sent} device${sent === 1 ? '' : 's'}${split}.`));
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
33
38
|
console.log(warning('No devices received it: has anyone enabled notifications in the app yet? (gipity notify subs)'));
|
|
39
|
+
}
|
|
34
40
|
if (pruned)
|
|
35
41
|
console.log(muted(` pruned ${pruned} expired subscription${pruned === 1 ? '' : 's'}`));
|
|
36
|
-
if (failed)
|
|
42
|
+
if (failed) {
|
|
37
43
|
console.log(muted(` ${failed} delivery failure${failed === 1 ? '' : 's'}`));
|
|
44
|
+
for (const r of results) {
|
|
45
|
+
if (r.status === 'failed' && r.transport === 'apns')
|
|
46
|
+
console.log(muted(` iOS device ...${r.device}: ${r.reason ?? 'failed'}`));
|
|
47
|
+
}
|
|
48
|
+
}
|
|
38
49
|
}));
|
|
39
50
|
notifyCommand
|
|
40
51
|
.command('subs')
|
|
@@ -50,12 +61,14 @@ notifyCommand
|
|
|
50
61
|
}
|
|
51
62
|
const { total, byUser } = res.data;
|
|
52
63
|
console.log(bold(`${total} subscription${total === 1 ? '' : 's'} across ${byUser.length} user${byUser.length === 1 ? '' : 's'}`));
|
|
53
|
-
for (const r of byUser)
|
|
54
|
-
|
|
64
|
+
for (const r of byUser) {
|
|
65
|
+
const split = r.ios > 0 ? ` (${r.web} web, ${r.ios} iOS)` : '';
|
|
66
|
+
console.log(` ${r.user_guid} ${muted(`${r.count} device${r.count === 1 ? '' : 's'}${split}`)}`);
|
|
67
|
+
}
|
|
55
68
|
}));
|
|
56
69
|
notifyCommand
|
|
57
70
|
.command('rm')
|
|
58
|
-
.description("Remove a user's push subscriptions (e.g. on account deletion)")
|
|
71
|
+
.description("Remove a user's push subscriptions and iOS devices (e.g. on account deletion)")
|
|
59
72
|
.requiredOption('--user <guid>', 'User guid whose subscriptions to remove')
|
|
60
73
|
.option('--project <guid-or-slug>', 'Target a specific project instead of cwd / Home')
|
|
61
74
|
.option('--json', 'Output raw JSON')
|
|
@@ -68,4 +81,84 @@ notifyCommand
|
|
|
68
81
|
}
|
|
69
82
|
console.log(success(`Removed ${res.data.removed} subscription${res.data.removed === 1 ? '' : 's'} for ${opts.user}.`));
|
|
70
83
|
}));
|
|
84
|
+
function printApns(c) {
|
|
85
|
+
if (!c.configured) {
|
|
86
|
+
console.log(warning('iOS push is not set up. Run: gipity notify apns set --team-id <id> --key-id <id> --p8 <AuthKey.p8> --bundle-id <id>'));
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
console.log(` Team ID: ${c.teamId}`);
|
|
90
|
+
console.log(` Key ID: ${c.keyId}`);
|
|
91
|
+
console.log(` Bundle ID: ${c.bundleId}`);
|
|
92
|
+
console.log(` Default: ${c.defaultEnvironment} ${muted('(for devices that register without an environment)')}`);
|
|
93
|
+
}
|
|
94
|
+
export const apnsCommand = new Command('apns')
|
|
95
|
+
.description('Set up push notifications for a native iOS app (your own Apple key)')
|
|
96
|
+
.addHelpText('after', `
|
|
97
|
+
Create an APNs key in your Apple Developer account (Certificates, Identifiers
|
|
98
|
+
& Profiles > Keys > + > Apple Push Notifications service), download the
|
|
99
|
+
AuthKey_<KEYID>.p8 file, then:
|
|
100
|
+
|
|
101
|
+
gipity notify apns set --team-id ABCDE12345 --key-id KEY1234567 \\
|
|
102
|
+
--p8 ./AuthKey_KEY1234567.p8 --bundle-id com.example.myapp
|
|
103
|
+
|
|
104
|
+
The key is stored encrypted and never shown again. Your app registers each
|
|
105
|
+
device with POST /api/<app-guid>/notify/devices; notify() then reaches it.`);
|
|
106
|
+
apnsCommand
|
|
107
|
+
.command('set')
|
|
108
|
+
.description('Store the APNs key for this app (all environments use it)')
|
|
109
|
+
.requiredOption('--team-id <id>', 'Your 10-character Apple Team ID')
|
|
110
|
+
.requiredOption('--key-id <id>', 'The 10-character Key ID of the APNs key')
|
|
111
|
+
.requiredOption('--p8 <file>', 'Path to the AuthKey_<KEYID>.p8 file')
|
|
112
|
+
.requiredOption('--bundle-id <id>', 'Your app bundle id, e.g. com.example.myapp')
|
|
113
|
+
.option('--sandbox', 'Devices that register without an environment use the sandbox (development builds)')
|
|
114
|
+
.option('--project <guid-or-slug>', 'Target a specific project instead of cwd / Home')
|
|
115
|
+
.option('--json', 'Output raw JSON')
|
|
116
|
+
.action((opts) => run('Notify', async () => {
|
|
117
|
+
const { config } = await resolveProjectContext({ projectOverride: opts.project });
|
|
118
|
+
let p8;
|
|
119
|
+
try {
|
|
120
|
+
p8 = readFileSync(opts.p8, 'utf-8');
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
throw new Error(`Can't read ${opts.p8}. Pass the path to the AuthKey_<KEYID>.p8 file from Apple.`);
|
|
124
|
+
}
|
|
125
|
+
const res = await put(`/api/${config.projectGuid}/services/notify/apns`, {
|
|
126
|
+
team_id: opts.teamId, key_id: opts.keyId, bundle_id: opts.bundleId, p8, sandbox: !!opts.sandbox,
|
|
127
|
+
});
|
|
128
|
+
if (opts.json) {
|
|
129
|
+
console.log(JSON.stringify(res.data));
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
console.log(success('✓ iOS push is set up.'));
|
|
133
|
+
printApns(res.data);
|
|
134
|
+
}));
|
|
135
|
+
apnsCommand
|
|
136
|
+
.command('show')
|
|
137
|
+
.description('Show the APNs setup for this app (never the key itself)')
|
|
138
|
+
.option('--project <guid-or-slug>', 'Target a specific project instead of cwd / Home')
|
|
139
|
+
.option('--json', 'Output raw JSON')
|
|
140
|
+
.action((opts) => run('Notify', async () => {
|
|
141
|
+
const { config } = await resolveProjectContext({ projectOverride: opts.project });
|
|
142
|
+
const res = await get(`/api/${config.projectGuid}/services/notify/apns`);
|
|
143
|
+
if (opts.json) {
|
|
144
|
+
console.log(JSON.stringify(res.data));
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
printApns(res.data);
|
|
148
|
+
}));
|
|
149
|
+
apnsCommand
|
|
150
|
+
.command('rm')
|
|
151
|
+
.description('Remove the APNs key (iOS devices stop receiving notifications)')
|
|
152
|
+
.option('--project <guid-or-slug>', 'Target a specific project instead of cwd / Home')
|
|
153
|
+
.option('--json', 'Output raw JSON')
|
|
154
|
+
.action((opts) => run('Notify', async () => {
|
|
155
|
+
const { config } = await resolveProjectContext({ projectOverride: opts.project });
|
|
156
|
+
const res = await del(`/api/${config.projectGuid}/services/notify/apns`);
|
|
157
|
+
if (opts.json) {
|
|
158
|
+
console.log(JSON.stringify(res.data));
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
console.log(res.data.removed ? success('✓ APNs key removed.') : warning('No APNs key was set.'));
|
|
162
|
+
}));
|
|
163
|
+
notifyCommand.addCommand(apnsCommand);
|
|
71
164
|
//# sourceMappingURL=notify.js.map
|
package/dist/commands/save.js
CHANGED
|
@@ -3,8 +3,10 @@
|
|
|
3
3
|
*
|
|
4
4
|
* A .gip is a zip of the project's file tree plus a reserved
|
|
5
5
|
* `_gip/manifest.json` metadata entry. It pairs with `gipity load`, which
|
|
6
|
-
* creates a brand-new project from a bundle.
|
|
7
|
-
*
|
|
6
|
+
* creates a brand-new project from a bundle. Secrets, custom domains, chats
|
|
7
|
+
* and app runtime uploads are never in a .gip. Database rows are left out
|
|
8
|
+
* unless the owner passes `--with-data` (every table's rows, up to the
|
|
9
|
+
* server's size cap); the schema always comes from the bundle's migrations.
|
|
8
10
|
*/
|
|
9
11
|
import fs from 'fs';
|
|
10
12
|
import path from 'path';
|
|
@@ -45,11 +47,14 @@ function dispositionFilename(headers) {
|
|
|
45
47
|
export const saveCommand = new Command('save')
|
|
46
48
|
.description('Save this app as a portable .gip bundle')
|
|
47
49
|
.argument('[output]', 'Output .gip path, or a directory to write <slug>.gip into (default: ./<slug>.gip)')
|
|
50
|
+
.option('--with-data', 'Also save every table\'s rows from the app\'s database (owner only)')
|
|
48
51
|
.option('--json', 'Output as JSON')
|
|
49
|
-
.addHelpText('after', '\nRestore anywhere with `gipity load <file>.gip` - it always creates a NEW project.'
|
|
52
|
+
.addHelpText('after', '\nRestore anywhere with `gipity load <file>.gip` - it always creates a NEW project.'
|
|
53
|
+
+ '\nWith --with-data, load also builds the database from the migrations and loads the rows.')
|
|
50
54
|
.action((output, opts) => run('Save', async () => {
|
|
51
55
|
const config = requireConfig();
|
|
52
|
-
const
|
|
56
|
+
const query = opts.withData ? '?with_data=1' : '';
|
|
57
|
+
const doExport = () => downloadWithHeaders(`/projects/${config.projectGuid}/export${query}`);
|
|
53
58
|
const { buffer, headers } = opts.json
|
|
54
59
|
? await doExport()
|
|
55
60
|
: await withSpinner('Exporting...', doExport, { done: null });
|
|
@@ -63,6 +68,9 @@ export const saveCommand = new Command('save')
|
|
|
63
68
|
const sha256 = createHash('sha256').update(buffer).digest('hex');
|
|
64
69
|
const skipped = Number(headers.get('x-gip-skipped') ?? 0);
|
|
65
70
|
const entries = zipEntryCount(buffer);
|
|
71
|
+
const data = opts.withData
|
|
72
|
+
? { tables: Number(headers.get('x-gip-data-tables') ?? 0), rows: Number(headers.get('x-gip-data-rows') ?? 0) }
|
|
73
|
+
: null;
|
|
66
74
|
if (opts.json) {
|
|
67
75
|
console.log(JSON.stringify({
|
|
68
76
|
path: dest,
|
|
@@ -70,6 +78,7 @@ export const saveCommand = new Command('save')
|
|
|
70
78
|
sha256,
|
|
71
79
|
...(entries !== null ? { entries } : {}),
|
|
72
80
|
skipped,
|
|
81
|
+
...(data ? { data } : {}),
|
|
73
82
|
}));
|
|
74
83
|
return;
|
|
75
84
|
}
|
|
@@ -78,12 +87,18 @@ export const saveCommand = new Command('save')
|
|
|
78
87
|
console.log(` Size: ${formatBytes(buffer.length)}`);
|
|
79
88
|
if (entries !== null)
|
|
80
89
|
console.log(` Entries: ${entries} (including the bundle manifest)`);
|
|
90
|
+
if (data)
|
|
91
|
+
console.log(` Data: ${data.rows} row(s) from ${data.tables} table(s)`);
|
|
81
92
|
console.log(` SHA-256: ${sha256}`);
|
|
82
93
|
if (skipped > 0) {
|
|
83
94
|
console.log('');
|
|
84
95
|
console.warn(warning(`${skipped} file(s) were skipped (unreadable or over 100 MB) - this bundle is partial.`));
|
|
85
96
|
console.warn(warning('Large assets belong in Gipity Storage, not in a code bundle.'));
|
|
86
97
|
}
|
|
98
|
+
if (data) {
|
|
99
|
+
console.log('');
|
|
100
|
+
console.warn(warning('This bundle holds the app\'s data. Share it only with people allowed to see that data.'));
|
|
101
|
+
}
|
|
87
102
|
console.log('');
|
|
88
103
|
console.log(muted('Restore anywhere with `gipity load ' + path.basename(dest) + '` (creates a new project).'));
|
|
89
104
|
}));
|