Repository Public
1#!/usr/bin/env swift2// =============================================================================3// SP BOUCHER | SOFTWARE & RESEARCH4// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5// =============================================================================6//7// PROJECT METADATA8// -----------------------------------------------------------------------------9// Project : ORIX Cosmos10// File : DataPipeline/packs/packsign.swift11// Module : DataPipeline12// Repository : https://git.spboucher.ai/orix-cosmos13// Project Website : https://www.orixlab.dev14// Created : 2026-11-2415// Last Modified : 2026-11-2416//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author : Simon-Pierre Boucher22// Position : Professor of Finance23// Institution : Université du Québec en Outaouais (UQO)24// Department : Département des sciences administratives25// Organization : SP Boucher26//27// Website : https://spboucher.ai28// Git : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General : info@spboucher.ai35// Professional : contact@spboucher.ai36// Direct : simon@spboucher.ai37// Research : research@spboucher.ai38// Development : dev@spboucher.ai39// Support : support@spboucher.ai40// Security/Admin : admin@spboucher.ai41// Notifications : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification : Public68// Distribution : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License : None specified (no license file in this repository)82// Maintainer : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889// ORIX Cosmos90// File: DataPipeline/packs/packsign.swift91// Description: Ed25519 key generation, manifest signing and signature verification for data packs (CryptoKit only; run with the Swift interpreter). Produces the manifest.sig format read by CosmosDataPacks.PackSignature.92//93// Author: Simon-Pierre Boucher94// Contact: contact@spboucher.ai95//96// Usage:97// swift DataPipeline/packs/packsign.swift keygen <private key file> new key pair; prints the public key and key id98// swift DataPipeline/packs/packsign.swift public <private key file> prints the public key and key id99// swift DataPipeline/packs/packsign.swift sign <pack dir> <private key file> writes <pack dir>/manifest.sig100// swift DataPipeline/packs/packsign.swift verify <pack dir> <public key base64>101//102// The private key file holds the raw 32-byte key in base64, mode 0600. It must live outside any git working tree:103// keygen refuses to write inside one. Sign last: any later change to manifest.json invalidates the signature.104import CryptoKit105import Foundation106107func fail(_ message: String) -> Never {108 FileHandle.standardError.write(Data(("error: " + message + "\n").utf8))109 exit(2)110}111112func hex(_ bytes: some Sequence<UInt8>) -> String { bytes.map { String(format: "%02x", $0) }.joined() }113func keyID(_ publicKey: Data) -> String { String(hex(SHA256.hash(data: publicKey)).prefix(16)) }114115func insideGitTree(_ url: URL) -> Bool {116 var dir = url.standardizedFileURL.deletingLastPathComponent()117 while dir.path != "/" {118 if FileManager.default.fileExists(atPath: dir.appendingPathComponent(".git").path) { return true }119 dir.deleteLastPathComponent()120 }121 return false122}123124func loadPrivateKey(_ path: String) -> Curve25519.Signing.PrivateKey {125 guard let text = try? String(contentsOfFile: path, encoding: .utf8),126 let raw = Data(base64Encoded: text.trimmingCharacters(in: .whitespacesAndNewlines)),127 let key = try? Curve25519.Signing.PrivateKey(rawRepresentation: raw) else { fail("cannot read an Ed25519 private key from \(path)") }128 return key129}130131func describe(_ key: Curve25519.Signing.PublicKey) {132 let raw = key.rawRepresentation133 print("publicKey: \(raw.base64EncodedString())")134 print("keyID: \(keyID(raw))")135}136137let args = Array(CommandLine.arguments.dropFirst())138switch (args.first, args.count) {139case ("keygen", 2):140 let url = URL(fileURLWithPath: args[1])141 if insideGitTree(url) { fail("refusing to write a private key inside a git working tree (\(url.path))") }142 if FileManager.default.fileExists(atPath: url.path) { fail("\(url.path) already exists") }143 let key = Curve25519.Signing.PrivateKey()144 let ok = FileManager.default.createFile(atPath: url.path, contents: Data((key.rawRepresentation.base64EncodedString() + "\n").utf8),145 attributes: [.posixPermissions: 0o600])146 if !ok { fail("cannot write \(url.path)") }147 describe(key.publicKey)148case ("public", 2):149 describe(loadPrivateKey(args[1]).publicKey)150case ("sign", 3):151 let dir = URL(fileURLWithPath: args[1], isDirectory: true)152 guard let manifest = try? Data(contentsOf: dir.appendingPathComponent("manifest.json")) else { fail("no manifest.json in \(dir.path)") }153 let key = loadPrivateKey(args[2])154 let id = keyID(key.publicKey.rawRepresentation)155 if let json = try? JSONSerialization.jsonObject(with: manifest) as? [String: Any] {156 if let announced = (json["signature"] as? [String: Any])?["keyID"] as? String {157 if announced != id { fail("manifest.json announces key \(announced), this key is \(id)") }158 } else {159 FileHandle.standardError.write(Data("warning: manifest.json has no signature block (packtool.py announce-signature); the signature is still valid\n".utf8))160 }161 }162 guard let signature = try? key.signature(for: manifest) else { fail("signing failed") }163 let doc = "{\n \"algorithm\" : \"ed25519\",\n \"keyID\" : \"\(id)\",\n \"signature\" : \"\(signature.base64EncodedString())\"\n}\n"164 do { try Data(doc.utf8).write(to: dir.appendingPathComponent("manifest.sig"), options: .atomic) } catch { fail("cannot write manifest.sig: \(error.localizedDescription)") }165 print("signed \(dir.appendingPathComponent("manifest.json").path) with key \(id)")166case ("verify", 3):167 let dir = URL(fileURLWithPath: args[1], isDirectory: true)168 guard let manifest = try? Data(contentsOf: dir.appendingPathComponent("manifest.json")),169 let sigData = try? Data(contentsOf: dir.appendingPathComponent("manifest.sig")),170 let doc = try? JSONSerialization.jsonObject(with: sigData) as? [String: Any],171 doc["algorithm"] as? String == "ed25519", let b64 = doc["signature"] as? String, let signature = Data(base64Encoded: b64) else {172 fail("cannot read manifest.json / manifest.sig in \(dir.path)")173 }174 guard let raw = Data(base64Encoded: args[2]), let key = try? Curve25519.Signing.PublicKey(rawRepresentation: raw) else { fail("bad public key") }175 if key.isValidSignature(signature, for: manifest) { print("OK: valid signature by key \(keyID(raw))") } else { print("INVALID signature"); exit(1) }176default:177 fail("usage: packsign.swift keygen <private key file> | public <private key file> | sign <pack dir> <private key file> | verify <pack dir> <public key base64>")178}179